Singleton
- Python course
- Advanced
- Lesson 61/83
- 5 min
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) # TrueThis 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._instancesuper().__new__(cls) is what actually creates the instance; we just do it once and store it.
Practice 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).
Starter code
# define the Singleton class
# add a class attribute to store the instance (None at first)
# write __new__: if not present, create with the parent's __new__ and store
# create two instances and print whether they are the sameSample 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)Expected output
True
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the second call return in the Singleton pattern?
- It raises an error
- A new instance
- Nothing
- The same instance Correct answer
Explanation: The Singleton returns the stored instance on the second call.
2 Complete the __new__ body
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().____(cls)
return cls._instance
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
Explanation: super().__new__(cls) creates the actual instance.
3 Match the Singleton concepts
| Term | Meaning |
|---|---|
_instance |
Stores the instance |
__new__ |
Creates the instance |
super().__new__ |
Makes the real instance |
a is b |
Means same object |