Weak References

Reference Counting

  • Normally, all Python objects are managed through reference counting
  • Reference counts modified by assignment, deletion, scopes, etc.
     a = Object()    # refcnt = 1
     b = a           # refcnt = 2
     c["foo"] = a    # refcnt = 3
     del b           # refcnt = 2

Weak reference

  • Mechanism for referring to object without increasing its reference count.
     import weakref
     a = Object()
     b = weakref.ref(a)    # Create weak reference to a
     ...
     obj = b()             # Dereference b
     if obj:
        # Do something
     else:
        # Object is gone!
<<< O'Reilly OSCON 2001, New Features in Python 2, Slide 39
July 26, 2001, beazley@cs.uchicago.edu
>>>