RFC: Proposal: Deterministic Object Destruction

Chris Angelico rosuav at gmail.com
Sun Mar 4 17:20:24 EST 2018


On Mon, Mar 5, 2018 at 9:09 AM, Richard Damon <Richard at damon-family.org> wrote:
> My presumption of the proposal is the it does NOT expect that __del__ be
> called just because an object is no longer reachable but is in a cycle of
> isolated objects, those would still need to wait for the garbage collector
> to get them. The request is that when the direct reference count goes to 0,
> that __del__ gets called.
>
> I think that is what CPython promises (but not other versions).
>
> I am not positive if __del__ gets called for sure when the object is garbage
> collected (I thought it did, but I am not positive).
>
> I am pretty sure it does NOT get called on object that are still in
> existence when things terminate (which would be the major difference from a
> language like C++)
>
> What the language does not promise is that in general, __del__ be called
> 'immediately' on the last reference going away in the general case, because
> CPythons reference counting is an implementation detail.
>
> My understanding of this proposal is to ask that, I would say at least for
> selected objects, that all implementations perform this reference counting,
> allowing objects that track 'critical resources' to get disposed of in a
> timely manner and not wait for garbage collection. And that this is
> triggered only by the reference count going to zero, and not if the object
> happens to be in an isolated reference cycle. This does limit what you can
> do with this sort of object, but that normally isn't a problem.

Okay, that sounds reasonable. Let's help things out by creating a
special syntax for reference-counted object usage, to allow other
implementations to use different forms of garbage collection. When you
acquire these kinds of objects, you "mark" them with this special
syntax, and Python will call a special method on that object to say
"hey, you're now in use". Then when that special syntax is done,
Python calls another special method to say "hey, you're not in use any
more". Something like this:

using some_object:
    ...
    ...
    ...
# at the unindent, we're automatically not using it

That would call a special method some_object.__now_using__() at the
top of the block, and some_object.__not_using__() at the bottom. Or,
if the block exits because of an exception, we could call
some_object.__not_using(exc) with the exception details. I think this
could be a really good feature - it'd allow non-refcounted Python
implementations to have a strong guarantee of immediate disposal of a
managed resource, and it'd also strengthen the guarantee for
refcounted Pythons too.

Feel free to bikeshed the exact keywords and function names, of course.

ChrisA



More information about the Python-list mailing list