Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weakref and __slots__

Tags:

People also ask

What does __ slots __ mean in Python?

Python | Use of __slots__ slots provide a special mechanism to reduce the size of objects.It is a concept of memory optimisation on objects.

What is __ Weakref __ in Python?

__weakref__ is just an opaque object that references all the weak references to the current object. In actual fact it's an instance of weakref (or sometimes weakproxy ) which is both a weak reference to the object and part of a doubly linked list to all weak references for that object.

How slots work Python?

Slots in Python is a special mechanism that is used to reduce memory of the objects. In Python, all the objects use a dynamic dictionary for adding an attribute. Slots is a static type method in this no dynamic dictionary are required for allocating attribute.

What is Weakref proxy?

weakref.proxy(object[,callback])Returns a proxy to the object that uses a weak reference. The returned object has type ProxyType or CallableProxyType, depending on if the object is callable. These objects are not hashable.


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?