__slots_ and inheritance

Alexander Schmolck a.schmolck at gmx.net
Thu Apr 10 15:39:47 CEST 2003


Paul Rubin <http://phr.cx@NOSPAM.invalid> writes:

> 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'd recommend against using __slots__ (unless really needed for optimization),
because it cripples the usefulness and generality of your classes to your and
also *to other people's* code (weakrefs, pickling, reflection -- all
compromised). The first two you could fix (but are unlikely to, unless you
*yourself* need to use weakrefs or pickling of instances of those classes),
the last one you can't.

The fact that someone's code using __slots__ makes other peoples code less
useful (because things that work fine for instances without slots suddenly
screw up) makes me think introducing __slots__ was a rather bad idea to start
with.


'as




More information about the Python-list mailing list