Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 417
readonly Avatar asked Mar 13 '26 20:03

readonly


1 Answers

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

like image 50
Blair Conrad Avatar answered Mar 15 '26 08:03

Blair Conrad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!