Question

How do you create a weak reference to an object in Python?

Was it helpful?

Solution

>>> 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top