Why cannot I use __slots__ and weakrefs together?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat May 26 05:17:22 EDT 2018


Here is my code:
---- cut here %< ----
import weakref
d = weakref.WeakValueDictionary()
class Spam:
 pass
class Eggs:
 __slots__ = ['spanish_inquisition']
d['a'] = Spam() # Okay.
d['b'] = Eggs() # Nobody will expect what happens next!
---- cut here %< ----
and the result I get is:
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "/usr/local/lib/python3.5/weakref.py", line 158, in __setitem__
 self.data[key] = KeyedRef(value, self._remove, key)
 File "/usr/local/lib/python3.5/weakref.py", line 306, in __new__
 self = ref.__new__(type, ob, callback)
TypeError: cannot create weak reference to 'Eggs' object
Why does weakref hate my Eggs class?
-- 
Steve


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /