[Python-ideas] weakrefs

Ethan Furman ethan at stoneleaf.us
Thu May 17 17:10:40 CEST 2012


 From the manual [8.11]:

 > A weak reference to an object is not enough to keep the object alive:
 > when the only remaining references to a referent are weak references,
 > garbage collection is free to destroy the referent and reuse its
 > memory for something else.

This leads to a difference in behaviour between CPython and the other 
implementations:  CPython will (currently) immediately destroy any 
objects that only have weak references to them with the result that 
trying to access said object will require making a new one; other 
implementations (at least PyPy, and presumably the others that don't use 
ref-count gc's) can "reach into the grave" and pull back objects that 
don't have any strong references left.

I would like to have the guarantees for weakrefs strengthened such that 
any weakref'ed object that has no strong references left will return 
None instead of the object, even if the object has not yet been garbage 
collected.

Without this stronger guarantee programs that are relying on weakrefs to 
disappear when strong refs are gone end up relying on the gc method 
instead, with the result that the program behaves differently on 
different implementations.

~Ethan~



More information about the Python-ideas mailing list