__slots_ and inheritance

Alex Martelli aleaxit at yahoo.com
Thu Apr 10 14:36:06 CEST 2003


Paul Rubin wrote:

> Alex Martelli <aleaxit at yahoo.com> writes:
>> __slots__ is, essentially, an optimization (in terms of memory
>> consumption) intended for classes that are likely to be created
>> in very large numbers: you give up the normal flexibility of
>> being able to add arbitrary attributes to an instance, and what
>> you gain in return is that you save one dictionary per instance
>> (dozens and dozens of bytes per instance -- that will, of course,
>> not be all that relevant unless the number of instances that are
>> around is at the very least in the tens of thousands).
> 
> I generally use __slots__ as a way to "declare" instance variables,
> so I get an exception if I accidentally assign to an undeclared one.
> I'd hope that was one of __slots__'s intended uses.

I don't see anything in __slots__'s well-documented design intent 
and behavior, http://www.python.org/2.2/descrintro.html &c, that
justifies such a "hope".  It may be feasible to have __slots__ do
double duty for that, if you don't need all the flexibility it's
going to lose you (e.g., no weak references, no "default values"
for instance variables through class variables...) AND you're in a 
very, VERY special case where no inheritance, __setattr__, access
to __dict__, or the like, can ever possibly impact your "hoped-for" 
functionality.  But, to me, such attempted "abuse" of __slots__ is
akin to using, say,
    hash(x)==x
as a way of testing whether "x is an integer-oid number" (handier
than int(x)==x because the latter fails when x is e.g. 23+0j) --
yeah, well, it works, sort of, but it's NOT what hash is meant for,
and you have no cause to complain if it doesn't work for your
purposes in any subtle or marginal case, or in the future.

If you really want to get an exception when an attribute is set
that you don't want to be set, you can use __setattr__, or a
custom metaclass.  __slots__ doesn't really help much here, IMHO.


Alex





More information about the Python-list mailing list