Sometimes (but not always) the __new__ method of one of my classes returns an *existing* instance of the class. However, when it does that, the __init__ method of the existing instance is called nonetheless, so that the instance is initialized a second time. For example, please consider the following class (a singleton in this case):
>>> class C(object): ... instance = None ... def __new__(cls): ... if C.instance is None: ... print 'Creating instance.' ... C.instance = object.__new__(cls) ... print 'Created.' ... return cls.instance ... def __init__(self): ... print 'In init.' ... >>> C() Creating instance. Created. In init. <__main__.C object at 0x4062526c> >>> C() In init. <---------- Here I want __init__ not to be executed. <__main__.C object at 0x4062526c> >>> How can I prevent __init__ from being called on the already-initialized object? I do not want to have any code in the __init__ method which checks if the instance is already initialized (like "if self.initialized: return" at the beginning) because that would mean I'd have to insert this checking code in the __init__ method of every subclass. Is there an easier way than using a metaclass and writing a custom __call__ method? -- Felix Wiemann -- http://www.ososo.de/ -- http://mail.python.org/mailman/listinfo/python-list