[Python-Dev] How to suppress instance __dict__?

David Abrahams dave@boost-consulting.com
Sun, 23 Mar 2003 18:18:26 -0500


Guido van Rossum <guido@python.org> writes:

> [Guido]
>> > __new__ creates a new, initialized object.  __init__ sets some values
>> > in an exsting object.  __init__ is a regular method and can be called
>> > to reinitialize an existing object (not that I recommend this, but the
>> > mechanism doesn't forbid it).  It follows that immutable objects must
>> > be initialized using __new__, since by the time __init__ is called the
>> > object already exists and is immutable.
>
> [David again]
>> Shouldn't most objects be initialized by __new__, really?  IME it's
>> dangerous to have uninitialized objects floating about, especially in
>> the presence of exceptions.
>
> Normally, there are no external references to an object until after
> __init__ returns

Good point; that's a feature you don't get unless you build two-phase
initialization into the core language.  Two-phase initialization is
more dangerous in C++ because it's not a core language feature.

> so you should be safe unless __init__ saves a reference to self
> somewhere.  It does mean that __del__ can be surprised by an
> uninitialized object, and that's a known pitfall.  And an exception
> in the middle of __new__ has the same problem.

C++ deals with that by only destroying the fully-initialized bases and
subobjects when an exception is thrown during construction.  That's
hard to do in the presence of two-phase initialization, though.  It
may be less of a problem for Python because __del__ is much less
commonly needed than nontrivial destructors are in C++.

> So I don't think __new__ is preferred over __init__, unless you need a
> feature that only __new__ offers (like initializing an immutable base
> class or returning an existing object or an object of a different
> class).

In other words, TIMTOWTDI? <0.3 wink>

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com