__slots_ and inheritance

Michael Hudson mwh at python.net
Thu Apr 10 12:15:33 EDT 2003


Jim Meyer <jmeyer at pdi.com> writes:

> On Thu, 2003-04-10 at 06:39, Alexander Schmolck wrote:
> > 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.
> 
> I'm feeling very slow this morning; could you give a few explicit
> examples of how __slots__ interferes with weakrefs, pickling, and
> reflection?

This sort of thing:

/>> class C(object):
|..  pass
\__ 
->> import weakref
->> weakref.ref(C())
<weakref at 8288a9c; dead>
/>> class C(object):
|..  __slots__ = []
\__ 
->> weakref.ref(C())
Traceback (most recent call last):
  File "<input>", line 1, in ?
TypeError: cannot create weak reference to 'C' object
/>> class C(object):
|..  __slots__ = ['__weakrefs__']
\__ 
->> weakref.ref(C())
Traceback (most recent call last):
  File "<input>", line 1, in ?
TypeError: cannot create weak reference to 'C' object
/>> class C(object):
|..  __slots__ = ['__weakref__']
\__ 
->> weakref.ref(C())
<weakref at 8276374; dead>
->> 

Cheers,
M.

-- 
    FORD:  Just pust the fish in your ear, come on, it's only a
           little one.
  ARTHUR:  Uuuuuuuuggh!
                    -- The Hitch-Hikers Guide to the Galaxy, Episode 1




More information about the Python-list mailing list