Ecir Hana Ecir Hana - 7 months ago 20
Python Question

Weakref and __slots__

Consider the following code:

from weakref import ref

class Klass(object):
# __slots__ = ['foo']
def __init__(self):
self.foo = 'bar'

k = Klass()
r = ref(k)


it works but when I uncomment the
__slots__
it breaks with
TypeError: "cannot create weak reference to 'Klass' object"
under Python 2.6.

Please, does anyone know if this is an inherent limitation of Python and
__slots__
or if it is a bug? How to work-around it?

Answer

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 ...>