How do you create a weak reference to an object in Python?
+9
A:
>>> 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
2008-09-08 23:13:16