Why cannot I use __slots__ and weakrefs together?

Gregory Ewing greg.ewing at canterbury.ac.nz
Sat May 26 06:04:42 EDT 2018


Steven D'Aprano wrote:
> TypeError: cannot create weak reference to 'Eggs' object
> 
> Why does weakref hate my Eggs class?

Classes with __slots__ aren't automatically given a __weakref__ slot,
to save memory I suppose.

But you can give it one explicitly:

 >>> class Eggs:
...   __slots__ = ['spanish_inquisition', '__weakref__']
...
 >>> e = Eggs()
 >>> d['b'] = e
 >>>

-- 
Greg



More information about the Python-list mailing list