CPython's cyclic garbage collector (was [Python-ideas] Automatic context managers)

Chris Angelico rosuav at gmail.com
Fri Apr 26 13:57:37 EDT 2013


On Sat, Apr 27, 2013 at 3:42 AM, Dave Angel <davea at davea.name> wrote:
> I don't see what your "special" temporary object actually accomplishes.
> Seems to me you need to declare that your __del__() methods promise not to
> reference each other, and the gc would then check all objects in the cycle,
> and do its present behavior if any of the destructors is not specially
> declared.

It wouldn't be declared; it'd simply throw an exception if anything
different happened.

> I'm not sure how often you'd have a non-trivial destructor that wouldn't
> reference any objects.  And doing a static analysis of what will happen
> during the destructor would be pretty messy.  So the best I and come up with
> is to keep the declaration, but require a try/catch to cleanly terminate
> each destructor if it ever references anything in the tree.

And yeah. If you catch the exception inside __del__, you can cope with
the destructed object yourself (or LBLY, if you wish). Alternatively,
you just proceed as normal, and when your __del__ throws an exception,
the gc then copes (not sure *how* it should cope - log it to stderr
and carry on?). Same as normal exception handling.

The advantage of this style is that the code to deal with the cycle is
kept right in the cyclic object's destructor - right where the problem
is. Doing it through gc.garbage requires that some other operation
periodically check for garbage - after the GC has done its own
periodic check. Seems simpler/cleaner to do it as part of the gc run
itself.

ChrisA



More information about the Python-list mailing list