RFC: Proposal: Deterministic Object Destruction (Posting On Python-List Prohibited)

Ian Kelly ian.g.kelly at gmail.com
Sat Mar 3 12:01:43 EST 2018


On Sat, Mar 3, 2018 at 9:19 AM, Richard Damon <Richard at damon-family.org> wrote:
> One idea does come to mind though, would it be reasonable, and somewhat
> Pythonic, for a class to define member functions like __ref__ and __unref__
> (or perhaps some other name) that if defined, would be called every time a
> name was bound or unbound to an object? (the assignment to a name should
> __ref__ the new value, then __unref__ the old to avoid possible issues with
> rebinding an object to the last name it was bound to). This would allow
> those (limited) objects that want to be destroyed as soon as possible to do
> so, but most other objects wouldn't have any significant overhead added
> (just a check for this method).
>
> Objects with these methods would still be subject to being cleaned up with
> garbage collection in the case they were kept alive via a cycle, having the
> cycle just makes it so that you don't get the immediate distruction.

This sounds like a nightmare for performance. Ref counting is enough
of a drain already when it's done in C, using macros for in-lining.
Now every time the count would be incremented or decremented, we'd
also need to check the class __dict__ to see if there's a
corresponding Python method, build a frame object, and then call it in
the interpreter.

And note that it would have to be basically any time the CPython
implementation currently adjusts the ref count, not just when a name
is bound or unbound, as there are lots of references that aren't
related to name bindings, for example:

* Objects stored in collections
* Function argument default values
* Function annotations
* References temporarily held by C-API code just to make sure that the
object they're manipulating doesn't suddenly become invalid during a
function call

It would be much more efficient to spare all that by doing the
ref-counting in the interpreter and just call a method when it hits
zero. Which is just what CPython already does.



More information about the Python-list mailing list