3.3.1 Weak Reference Objects
Description: Weak Reference Objects
Keywords: lib

##
3.3.1 Weak Reference Objects

Weak reference objects have no attributes or methods, but do allow the referent to be obtained, if it still exists, by calling it:

    >>> import weakref
    >>> class Object:
    ...     pass
    ...
    >>> o = Object()
    >>> r = weakref.ref(o)
    >>> o2 = r()
    >>> o is o2
    True

If the referent no longer exists, calling the reference object returns `None`:

    >>> del o, o2
    >>> print r()
    None

Testing that a weak reference object is still live should be done using the expression `ref() is not None`. Normally, application code that needs to use a reference object should follow this pattern:

    # r is a weak reference object
    o = r()
    if o is None:
        # referent has been garbage collected
        print "Object has been allocated; can't frobnicate."
    else:
        print "Object is still live!"
        o.do_something_useful()

Using a separate test for ``liveness'' creates race conditions in threaded applications; another thread can cause a weak reference to become invalidated before the weak reference is called; the idiom shown above is safe in threaded applications as well as single-threaded applications.