11

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

Blair Conrad
  • 233,004
  • 25
  • 132
  • 111
readonly
  • 343,444
  • 107
  • 203
  • 205

1 Answers1

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