WeakValueDictionary
Andrew Dalke
adalke at mindspring.com
Sun Oct 3 02:56:43 EDT 2004
Bryan wrote:
> i have another question about weak references. how do you know that b
> is dead?
>
>
> >>> a = A()
> >>> b = weakref.ref(a)
> >>> b
> <weakref at 011739F0; to 'instance' at 01135CB0>
> >>> del a
> >>> b
> <weakref at 011739F0; dead>
Quoting from the weakref PEP at
http://www.python.org/peps/pep-0205.html
A weak reference object will allow access to the referenced object
if it hasn't been collected and to determine if the object still
exists in memory. Retrieving the referent is done by calling the
reference object. If the referent is no longer alive, this will
return None instead.
>>> class Spam:
... def hello(self): print "Hello!"
...
>>> a = Spam()
>>> b = weakref.ref(a)
>>> b().hello()
Hello!
>>> del a
>>> b().hello()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'NoneType' object has no attribute 'hello'
>>> b()
>>> b() is None
True
>>>
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list