Python Singleton Class: Implementing the Singleton Design Pattern
Learn about Singleton classes in Python and how they ensure only one instance of a class is created. Discover methods for implementing Singleton classes using __init__
and __new__
to optimize memory usage and manage resources efficiently.
Python - Singleton Class
Introduction
In Python, a Singleton class is the implementation of the singleton design pattern, which ensures that a class can have only one object. This helps optimize memory usage for heavy operations like creating a database connection. If multiple objects are created for a singleton class, only the first object is created, and subsequent instances return the same object.
Creating Singleton Classes in Python
Singleton classes in Python can be implemented using the following methods:
- Using
__init__
- Using
__new__
Using __init__
The __init__
method is an instance method used for initializing a newly created object. It’s automatically called when an object is created from a class. To create a singleton class using this method, we need to check if an instance of the class already exists and restrict the creation of a new object after the first one.
Example
class Singleton:
__uniqueInstance = None
@staticmethod
def createInstance():
if Singleton.__uniqueInstance == None:
Singleton()
return Singleton.__uniqueInstance
def __init__(self):
if Singleton.__uniqueInstance != None:
raise Exception("Object already exists!")
else:
Singleton.__uniqueInstance = self
# Creating instances
obj1 = Singleton.createInstance()
print(obj1)
obj2 = Singleton.createInstance()
print(obj2)
Output
<__main__.Singleton object at 0x7e4da068a910>
<__main__.Singleton object at 0x7e4da068a910>
Using __new__
The __new__
method is a special static method called to create a new instance of a class. It takes the class itself as the first argument and returns a new instance of that class. To implement a Singleton class using __new__
, we override this method, check if an instance of the class already exists, and create a new object only if it doesn't.
Example
class SingletonClass:
_instance = None
def __new__(cls):
if cls._instance is None:
print('Creating the object')
cls._instance = super(SingletonClass, cls).__new__(cls)
return cls._instance
# Creating instances
obj1 = SingletonClass()
print(obj1)
obj2 = SingletonClass()
print(obj2)
Output
Creating the object
<__main__.SingletonClass object at 0x000002A5293A6B50>
<__main__.SingletonClass object at 0x000002A5293A6B50>