In a classic singleton in Python, we check whether an instance is already created. If it is created, we return it; otherwise, we create a new instance, assign it to a class attribute, and return it.
Let's try to create a dedicated singleton class:
class Singleton(object): def __new__(cls): if not hasattr(cls, 'instance'): cls.instance = super(Singleton, cls).__new__(cls) return cls.instance
Here, before creating the instance, we check for the special
__new__ method that is called right before
__init__ if we had created an instance earlier. If not, we create a new instance; otherwise, we return the already created instance.
Let's check how it works:
>>> singleton = Singleton() >>> another_singleton = Singleton() >>> singleton is ...