I'm trying to implement a singleton in Python, and after reading this post I find myself even more confused than before. There are way too many answers, and many of them have received their fair number of votes. Now the problem may not be that I have a singleton, but the fact that the state has to be initialized only once. I tried a couple of implementations SingletonA
and SingletonB
but I can't manage this to work. For my real problem, the __init__
function is quite heavy so I have to do it only once. This is what I have so far:
class ClassA:
def __init__(self):
# some state
print("Creating state in A")
self.X = 1.
self.Y = 2.
class SingletonA(ClassA):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(SingletonA, cls).__new__(
cls, *args, **kwargs)
return cls._instance
class ClassB:
__shared_state = {}
def __init__(self):
if not bool(ClassB.__shared_state):
# some state
print("Creating state in B")
self.X = 1.
self.Y = 2.
self.__dict__ = self.__shared_state
def singleton(cls):
obj = cls()
# Always return the same object
cls.__new__ = staticmethod(lambda cls: obj)
# Disable __init__
try:
del cls.__init__
except AttributeError:
pass
return cls
@singleton
class SingletonB(ClassB):
pass
if __name__ == "__main__":
a1 = SingletonA()
a2 = SingletonA()
if (id(a1) == id(a2)):
print("Same",a1.X, a1.Y)
else:
print("Different",a1.X, a1.Y)
b1 = SingletonB()
b2 = SingletonB()
if (id(b1) == id(b2)):
print("Same",b1.X, b1.Y)
else:
print("Different",b1.X, b1.Y)
Now this is printing:
$ python singleton.py
Creating state in B
Creating state in B
Same 1.0 2.0
Creating state in A
Creating state in A
Same 1.0 2.0
Pointing to the fact that indeed I have a singleton class, but I want to avoid the creation of state.