Website hosting service by Active-Venture.com
  

 Back to Index


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.

 

  

 

2002-2004 Active-Venture.com Webhosting Service

 

Disclaimer: This documentation is provided only for the benefits of our hosting customers.
For authoritative source of the documentation, please refer to http://python.org/doc/

 

Cheap domain registration : Register domain name or buy domain name, including free domain hosting services

 
Active-Domain.com offers cheap domain registration, domain name transfer and domain search services    

Domain registration : Buy domain name or register domain name from $5.95/year only