__slots_ and inheritance
Michael Chermside
mcherm at mcherm.com
Fri Apr 11 11:03:27 EDT 2003
As Alexander Schmolck has so eloquently explained, use of __slots__ (which is
intended simply as a speed-and-memory optimization) breaks several things...
among them:
1. It breaks weakrefs (can't make a weakref to a __slots__ object).
2. It breaks pickling (can't pickle a __slots__ object without custom code).
3. It breaks introspection (eg: can't call vars() on a __slots__ object).
4. It breaks "decoration" with new attributes (can't add new attributes
if object has no __dict__).
Of these, #4 was intentional, but I don't see any reason for the others!
For instance, introspection (most of it anyhow) could be enabled for
__slots__ objects by modifying vars() (and several other things) to
check the __slots__ for a list of additional values. Pickling too could
set and get values listed in __slots__. I haven't any idea what the
issue with weakrefs would be.
So can anyone out there tell me if these are (a) planned, but not done
yet, or (b) welcome, patches would be appreciated, or (c) difficult or
impossible for some reason I'm not aware of.
-- Michael Chermside
PS: There are also a few breakages that I really don't care about. Eg:
5. Problems if a subclass re-declares a variable already in use.
6. No "default values" for instances through class variables.
7. Things don't work right if you modify __slots__.
I'd say "just don't do that". If you need such things, don't use
__slots__.
More information about the Python-list
mailing list