Recently, I am considering how to implement a Singleton pattern in Python. The following code works fine if the Singleton class has no subclasses.
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
However, the Singleton class may have subclasses.
class SingletonSub1(Singleton):
def __new__(cls, *args, **kwargs):
return super(SingletonSub1, cls).__new__(cls, *args, **kwargs)
class SingletonSub2(Singleton):
def __new__(cls, *args, **kwargs):
return super(SingletonSub1, cls).__new__(cls, *args, **kwargs)
The requirement is that you can have only 1 instance in the system which is Singleton, SingletonSub1, or SingletonSub2. How can I implement this? I know I can definitely use a module level variable to hold the Singleton object. But it is really a bad code...