Singleton pattern in python - Fri, Nov 11, 2022
Singleton pattern in python
This snippet contains the implementation of a singleton pattern in python:
class Singleton:
__instance = None
def __init__(self):
print("Singleton.__init__, do nothing") # This method gets called multiple times
def __new__(cls):
if not cls.__instance:
cls._instance = super(Singleton, cls).__new__(cls)
# Initialize the instance here instead of __init__ to avoid re-initialization
return cls.__instance
if __name__ == '__main__':
s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # True
# Print the memory address of the two instances
print(hex(id(s1)))
print(hex(id(s2)))
First take a look at the class Singleton
. The key point here is that whenever a class is instantiated the method __new__
is called to create the object.
In the singleton above we override this method and check whether an instance has already been created or not. If no instance has yet been created
we create one and store it as a class variable. The next time someone tries to instantiate the class, the same class instance is returned instead
of a new one.
The output of running this code should look like this:
Singleton.__init__, do nothing
Singleton.__init__, do nothing
True
0x7f9a6dc9fcd0
0x7f9a6dc9fcd0
You might have noticed that __init__
has been called twice despite the instance being the same. That’s why initialization code
for this singleton should not be put in the __init__
method but rather be done after instance creation (see comment in line 30
).
Things might get even a bit more complicated when the singleton inherits from another class.
A full example with inheritance can be found here
.