Source: Python and the Singleton Pattern
According to most upvoted comment in the top answer init gets called multiple times if new returns class instance.
So I checked this:
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
print 'Singleton.__new__ called with class', cls
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
class Cache(Singleton):
def __init__(self, size=100):
print 'I am called with size', size
class S(Singleton):
def __init__(self, param):
print 'I am S with param', param
c = Cache(20)
s = S(10)
Result:
Singleton.__new__ called with class <class '__main__.Cache'>
I am called with size 20
Singleton.__new__ called with class <class '__main__.S'>
I am S with param 10
Apparently init does not called more than once in a class inheriting from Singleton. Has smth changed in Python that handles this in the meantime (considering the question was asked in 2008), or am I missing smth here?