Why cannot I use __slots__ and weakrefs together?
Christian Heimes
christian at python.org
Sat May 26 05:53:42 EDT 2018
On 2018-05-26 11:17, Steven D'Aprano wrote:
> 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?
Weakref needs some place to store reference information. It works if you
add "__weakref__" to your slots:
class Eggs:
__slots__ = ['spanish_inquisition', '__weakref__']
Christian
More information about the Python-list
mailing list