Can __new__ prevent __init__ from being called?

Peter Hansen peter at engcorp.com
Tue Feb 15 17:09:27 EST 2005


Felix Wiemann wrote:
> 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):
> 
[snip]
> How can I prevent __init__ from being called on the already-initialized
> object?

Is this an acceptable kludge?

 >>> class C(object):
...  instance=None
...  def __new__(cls):
...   if C.instance is None:
...    print 'creating'
...    C.instance = object.__new__(cls)
...   else:
...    cls.__init__ = lambda self: None
...   return cls.instance
...  def __init__(self):
...   print 'in init'
...
 >>> a = C()
creating
in init
 >>> b = C()
 >>>

(Translation: dynamically override now-useless __init__ method.
But if that works, why do you need __init__ in the first place?)

-Peter



More information about the Python-list mailing list