GNU Info

Info Node: (python2.1-lib.info)Weak Reference Objects

(python2.1-lib.info)Weak Reference Objects


Next: Example Prev: weakref Up: weakref
Enter node , (file) or (file)node

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
     1

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.get() is not None'.  Normally, application code
that needs to use a reference object should follow this pattern:

     o = ref.get()
     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 `get()' method is called; the idiom shown
above is safe in threaded applications as well as single-threaded
applications.


automatically generated by info2www version 1.2.2.9