How to create weak object reference in Python?

How to create weak object reference in Python?

+5
source share
1 answer
>>> 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 wearkref docs for more information. You can also use weakref.proxyto create an object that proxies o. Throws ReferenceErrorif used when the referent is no longer referenced.

+11
source

All Articles