Notification when reference count goes to 0?

Erik Max Francis max at alcyone.com
Mon Dec 23 02:13:26 EST 2002


Robert Oschler wrote:

> Is there a way to get notification when the reference count goes to 0
> on an
> object? The only thing I miss from C++ is destructors.  If there was a
> way
> to get notified when an object's reference count went to 0, the
> automatic
> release of associated resources would be possible, yes?

There is the __del__ method which _may_ be called _at some point_ after
the last reference to an object goes away, but it really is a finalizer,
rather than a destructor, since you've really on guarantees on precisely
when (or even if, in the case where you have circular references) it
will be called.

That being said, in the CPython implementation, the __del__ method _is_
called as soon as the last reference goes away.  However, Python as a
language does not make you this guarantee, and quite frankly there
probably aren't any solid assurances that this wouldn't change in a
future version of CPython (although it is probably highly unlikely).

> Just to be
> explicit, I'm not interested in garbage collection based finalization,
> as
> everyone knows the timing or even the occurrence of such an event
> comes
> under the heading of 'unspecified behavior', at least with Java it is.

Since you don't want finalizers, the big answer to your question is,
"No, there is no way," but if you know you're restricting yourself to
the CPython implementation, then you could use the __del__ method (with
the caveat that you _will_ be relying on the unspecified behavior you
rightly want to avoid).

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ Whoever named it necking was a poor judge of anatomy.
\__/ Groucho Marx
    CAGE / http://www.alcyone.com/pyos/cage/
 A cellular automaton simulation system in Python.



More information about the Python-list mailing list