How do you create a weak reference to an object in Python?
Asked
Active
Viewed 902 times
1 Answers
14
>>> import weakref
>>> class Object:
... pass
...
>>> o = Object()
>>> r = weakref.ref(o)
>>> # if the reference is still active, r() will be o, otherwise None
>>> do_something_with_o(r())
See the wearkref module docs for more details.
You can also use weakref.proxy
to create an object that proxies o. Will throw ReferenceError
if used when the referent is no longer referenced.

Blair Conrad
- 233,004
- 25
- 132
- 111