modifying __new__ of list subclass

Alex Martelli aleax at mac.com
Tue Aug 15 11:04:19 EDT 2006


Ken Schutte <kschutte at csail.mit.edu> wrote:

> Steven Bethard wrote:
> > 
> > The __new__ method is for immutable types.  So things like str and int
> > do their initialization in __new__.  But for regular mutable types, you
> > should do your initialization in __init__::
> 
> I see... So, is there a use for __new__ in mutable types?   From my 
> list-derirved class, it was obviously being called, but it's return 
> value is totally ignored?

Wrong: the return value of __new__ is most definitely NOT "totally
ignored", since it's what gets passed as the first argument of __init__
(as long as it's an instance of the type in question).  Easy to check
for yourself, e.g.:

>>> class ha(list):
...   def __new__(cls, *a):
...     x = list.__new__(cls, *a)
...     x.foo = 23
...     return x
... 
>>> z = ha()
>>> z.foo
23
>>> 

as you can see, the "totally ignored" hypothesis is easily disproved.

Of course, there's no particular reason why class ha would _want_ to set
the .foo attribute in __new__ rather than __init__, so that doesn't yet
answer your other question about "is there a use".  That answer is a
resounding "yes", but the uses may be subtler than you're considering:
for example, you may use the subtype as a general-purpose "factory", so
that instantiating the subtype may return objects that are not in fact
instances of the subtype (that bypasses the __init__ call); or, the
overriding of __new__ may go together with the overriding of __init__
(so that the latter doesn't blast the object's state) for such purposes
as singletons or more generally types with a finite "pool" of instances.


Alex




More information about the Python-list mailing list