Consider the following code:
from weakref import ref
# __slots__ = ['foo']
self.foo = 'bar'
k = Klass()
r = ref(k)
TypeError: "cannot create weak reference to 'Klass' object"
__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
From the Python documentation.
If you add
__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 ...>