Python vs Java garbage collection?

Paul Moore gustav at morpheus.demon.co.uk
Sun Dec 29 10:08:14 EST 2002


"Robert Oschler" <Oschler at earthlink.net> writes:

> "Martin v. Löwis" <martin at v.loewis.de> wrote in message
> news:au83ji$4fa$00$1 at news.t-online.com...
>
>> I see. This is precisely the definition of Python's __del__ method:
>> it is called when the reference count drops to zero, atleast for
>> CPython.
>>
>
> True, but unless I misread the previous posts in this thread, the
> language spec does not guarantee this behavior, even for CPython,
> and therefore taking advantage of it might "break" something in the
> future.  If it became a guaranteed item then that would be great.
> Xmas? :)

The language spec does not guarantee the existence of a concept of
"the reference count" of an object. All the spec says about __del__ is
that it is "called when the instance is about to be destroyed".
Unfortunately, this statement is too weak to be of much practical
value.

For many practical uses, relying on CPython's reference counting
semantics is both useful and understandable. But it doesn't always
give you the results you'd like (cycles, and destruction of objects
alive at program termination being the 2 obvious cases). And you are
risking portability if you rely on this behaviour.

Portability to Jython is easy enough to check (Jython has no reference
counting, and so the timing of __del__ calls is not deterministic).
Portability to a not-yet-created implementation of Python is not
checkable, in general - it's hard to see why anyone really cares about
this, for anything other than theoretical reasons, though.

In theory, an entirely valid implementation of Python (the language)
could allocate objects and *never* delete them, even when they become
inaccessible. (This would have sub-optimal memory consumption
characteristics, of course :-)) In such an implementation, __del__
would never be called.

Does this make __del__ useless? I doubt it...

On the other hand, guaranteeing deterministic __del__ behaviour does
pretty much force the implementation to use reference counting.  And
while refcounts have been a reasonably good GC mechanism in CPython
for a long time now, they certainly aren't the final word on the
subject.  And as Jython shows, they may not be sensible to implement.
So I don't imagine that deterministic __del__ behaviour will be
mandated in the forseeable future.

Paul.
-- 
This signature intentionally left blank



More information about the Python-list mailing list