What are the differences between _weak_ references and "normal" references?

Erik Max Francis max at alcyone.com
Fri Apr 4 17:43:57 EST 2003


Jp Calderone wrote:

>   Weak references to objects don't increment the refcount for that
> object.

Right.  And an importang thing to point out from someone with a C++
background is that weak references understand when their referent is
gone, and won't run off into segmentation fault land.  (In C++, you can
delete the referent, but the reference itself will have no idea and will
gladly dereference it.)

>>> import weakref
>>> class C: pass
... 
>>> c = C() # create an object
>>> 
>>> c1 = weakref.ref(c) # and a weak reference to it
>>> c1
<weakref at 0x81593a4; to 'instance' at 0x815a214>
>>> c1() # call the reference to get the referent
<__main__.C instance at 0x815a214>
>>> del c # now the weak reference is dead
>>> c1
<weakref at 81593a4; dead>
>>> c1()
>>> c1() is None # now the referent is None
1

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ If the sky should fall, hold up your hands.
\__/ (a Spanish proverb)
    The laws list / http://www.alcyone.com/max/physics/laws/
 Laws, rules, principles, effects, paradoxes, etc. in physics.




More information about the Python-list mailing list