Code:
from weakref import WeakSet
se = WeakSet()
se.add(1)
Output:
TypeError: cannot create weak reference to 'int' object
Doc:
Several built-in types such as list and dict do not directly support weak references but can add support through subclassing:
...
Other built-in types such as tuple and int do not support weak references even when subclassed (This is an implementation detail and may be different across various Python implementations.).
This isn't expressive enough to explain:
Why some built-in types don't support weak references?
What are exactly those types that support weak references?
To add some thoughts:
For the above example you can wrap the int within a user-defined wrapper class, and that wrapper class supports weak references (Those who are familiar with Java will recall int
and Integer
):
from weakref import WeakSet
se = WeakSet()
class Integer:
def __init__(self, n=0):
self.n = n
i = 1
I = Integer(1)
se.add(i) # fail
se.add(I) # ok
I'm not sure why Python doesn't provide auto-wrapping for commonly used built-in types (int
, str
, etc.) but instead simply say they don't support weak references. It might be due to performance issues, but not being able to weakref these built-in types greatly reduced its usage.