Weakref proxy is for instance only ...
Proxy cannot be created for basic datatypes like list, dict, str and int. Proxy can be create for class instances only. Also proxy cannot be created for proxy of another instance.
>>> import weakref
>>> a = 'str'
>>> b = weakref.proxy(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot create weak reference to 'str' object
>>> a = 1
>>> b = weakref.proxy(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot create weak reference to 'int' object
>>> a = []
>>> b = weakref.proxy(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot create weak reference to 'list' object
>>> a = {}
>>> b = weakref.proxy(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot create weak reference to 'dict' object
>>> class A(object): pass
...
>>> a = A()
>>> b = weakref.proxy(a)
>>> c = weakref.proxy(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot create weak reference to 'weakproxy' object
To avoid creating proxy for another proxy, ProxyTypes can be used to check if the passed var is a proxy type and create proxy only if required
>>> a = A()
>>> b = weakref.proxy(a)
>>> type(b) in weakref.ProxyTypes
True
>>> type(b)
<type 'weakproxy'>
>>> weakref.ProxyTypes
(<type 'weakproxy'>, <type 'weakcallableproxy'>)
Comments