[Python-Dev] pep 422 "Safe object finalization" question: why break weakrefs first?

Antoine Pitrou solipsis at pitrou.net
Tue May 28 21:37:15 CEST 2013


On Tue, 28 May 2013 12:21:25 -0700
"Russell E. Owen" <rowen at uw.edu> wrote:
> Pep 422 proposes the following order for dealing with cyclic isolates:
> 
>    1. Weakrefs to CI objects are cleared, and their callbacks called. At 
> this point, the objects are still safe to use.
>    2. The finalizers of all CI objects are called.
>    3. The CI is traversed again to determine if it is still isolated. If 
> it is determined that at least one object in CI is now reachable from 
> outside the CI, this collection is aborted and the whole CI is 
> resurrected. Otherwise, proceed.
>    4. The CI becomes a CT as the GC systematically breaks all known 
> references inside it (using the tp_clear function).
> 
> Why are weakrefs are broken first, before determining if any of the 
> objects should become resurrected? Naively I would expect weakrefs to be 
> broken after step 3, once the system is sure no objects have been 
> resurrected.

The answer is that this is how weakrefs currently work: they are
cleared (and their callbacks executed) before __del__ is executed,
therefore if __del__ revives the object, the weakrefs stay dead.
The rationale is simply to minimize disruption for existing code.
However, the PEP would indeed make it possible to change that behaviour,
if desired.

You can read
http://hg.python.org/cpython/file/4e687d53b645/Modules/gc_weakref.txt
for a detailed (and lengthy) explanation of why weakrefs work that way
right now.

Regards

Antoine.




More information about the Python-Dev mailing list