Weakref and __slots__ Weakref and __slots__ python python

Weakref and __slots__


Without a __weakref__ variable for each instance, classes defining __slots__ do not support weak references to its instances. If weak reference support is needed, then add __weakref__ to the sequence of strings in the __slots__ declaration.

From the Python documentation.

If you add __weakref__ to __slots__, your code will work:

>>> from weakref import ref>>>>>> class Klass(object):>>>     __slots__ = ['foo', '__weakref__']>>>     def __init__(self):>>>         self.foo = 'bar'>>> k = Klass()>>> k => <__main__.Klass object at ...>>>> r = ref(k)>>> r => <weakref at ...; to 'Klass' at ...>


You have to add __weakref__ to the list of slots. It's one of the __slots__ quirks. Prior to 2.3, even this didn't work, but luckily your version isn't that old.