Python
Singleton
Learn to write the Singleton pattern in Python.
Singleton
The Singleton pattern ensures only one instance of a class is created. By overriding __new__, the first call stores the instance and later calls return the same one.
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
a = Singleton()
b = Singleton()
print(a is b) # True
This pattern is used for objects that should be unique, such as configuration, a connection pool or a logger.
The __new__ method
__new__ is the method that creates a new instance of a class. It is called before __init__. In Singleton, if cls._instance is None, it creates the instance with super().__new__(cls) and stores it.
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
super().__new__(cls) is what actually creates the instance; we just do it once and store it.
Exercise Write a Singleton class
Define class Singleton:. Add class attribute _instance = None. Write def __new__(cls): that does if cls._instance is None: cls._instance = super().__new__(cls) then return cls._instance. Create two instances a = Singleton() and b = Singleton(). Print whether they are the same with print(a is b).
Show example solution
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
a = Singleton()
b = Singleton()
print(a is b)
Test yourself
-
What does the second call return in the Singleton pattern?
- It raises an error
- A new instance
- Nothing
- The same instance
Show answer
The same instance — The Singleton returns the stored instance on the second call.
-
Complete the __new__ body
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().____(cls)
return cls._instance
Show answer
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
-
Match the Singleton concepts
- _instance
- Stores the instance
- __new__
- Creates the instance
- super().__new__
- Makes the real instance
- a is b
- Means same object
Next lesson: Factory