beginner's refcount questions

Scott David Daniels scott.daniels at acm.org
Sun Oct 29 21:07:49 EST 2006


Jens Theisen wrote:
> python uses gc only where refcounts alone haven't yet done the
> job. Thus, the following code
>     class Foo:
>         def __del__(self):
>            print "deled!"
... In c++, this is a central technique used for all sorts of tasks,
whereas in garbage collected languages it's usually not available.

> Is there a reason not to rely on this in Python? For example, are
> there alternative Python implementations that behave differently?  Or
> some other subtle problems?

Python (the language) does not guarantee when (or even if) __del__
methods will be invoked, while C++ does (for the corresponding method).
Jython relies on Java's GC, IronPython?....  CPython's garbage collector
(which finds loops of references and drops them as a group) avoids
any loops containing more than a single __del__ method.  In the spirit
of "explicit is better than implicit," ignore this problem and stop
using __del__.  In some cases you might want to check into the semantics
of the "with" construct introduced in 2.5, it may allow you to do what
you really mean.

> And some other minor question: Is there a way to query the use count
> of an object? This would be useful for debugging and testing.
     >>> import sys
     >>> sys.getrefcount(42 * 7)
     2

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list