__slots__

Alex Martelli aleax at aleax.it
Mon Nov 10 11:32:57 EST 2003


flori wrote:
   ...
> class _ca(object): pass
> class ca(object): __slots__ = ("a",)
> class _cb(_ca): pass
> class cb(_cb): __slots__ = ("a","b")
> class _cc(_ca): pass
> class cc(_cc): __slots__ = ("a","c")
> class _cd(_cb,_cc): pass
> class cd(_cd): __slots__ = ("a","b","c","d")
> 
> my source does this a metaclass
> 
> my question is is their a nicer way to do this?

Yes: and the nicer way to get exactly the same result is,
remove all those useless __slots__ declarations.  What do
you think they're buying you...?

Maybe you haven't tried the elementary test...:

x = cd()
x.pippo = 'ma va!'
print x.pippo

...?

Once _any_ base class allows instances to have a per-instance
dictionary (which is the case for all classes _except_ the very
special ones where we insert the very-special-purpose and often-
misunderstood *optimization* '__slots__'....), then of course
*all* instances of that class (and an instance of a subclass is
an instance of the base class too) will have a per-instance
dictionary.  And once you have a per-instance dictionary anyway,
adding __slots__ is just silly -- can't make the per-inst dict
disappear, so no memory is actually saved, no attribute setting
is prohibited, etc, etc.

And yes, you can't multiply inherit from several classes that
define __slots__ (not even identical slots, if I recall correctly),
just like you can't multiply inherit from different built-in
types (with non-null instance-layout constraints), nor even from
one built-in type and a separate class with __slots__.  Defining
__slots__ does constrain the instance layout, and generally speaking
Python doesn't even _try_ to sort out any case of multiple separate
constraints on instance layout.

__slots__ is meant as a special-purpose memory optimization to
save the per-instance memory cost of a dictionary when you're
defining small classes of which a huge number of instances are
meant to exist at the same time, so that the several tens of bytes
per instance that a dictionary might cost is an unacceptable price
to pay compared to the "actual" footprint of each of the huge
number of instances.  For this use case, which is really the only
one that __slots__ is intended for, multiple inheritance isn't
really indispensable.  All in all, I doubt, therefore, that these
limitations will go away.


Alex






More information about the Python-list mailing list