Python vs Java garbage collection?
"Martin v. Löwis"
martin at v.loewis.de
Mon Dec 23 17:59:19 EST 2002
Erik Max Francis wrote:
> As he already said, he was referring to destructors in conjunction with
> reference counting entities in C++, such as std::auto_ptr.
std::auto_ptr is no reference counting entity (it does not count
references). Addition of reference counting entities would not change
anything for Python, atleast CPython already has reference counting
entities (*all* entities are reference counted).
So if you use std::auto_ptr as a class member in C++, you can literally
translate your code to Python (just omit the auto_ptr), and it literally
works the same way with respect to finalization (atleast if you use
CPython): If the container goes away, and it was holding the only
reference (as is a requirement for std::auto_ptr), the contained is
finalized immediately.
What he *might* be thinking of (but he just explained something
completely different) is that he wants to have lexically-scoped
references, or lifetime: if you have a reference in a local variable of
a function, and the function terminates, you want the reference to be
released or the object to terminate its life.
In the case of terminate-its-life, I see a semantic difficulty extending
this to Python: What if there are other references to the same object?
This is no language-specification problem in C++: if you access the dead
object through a dangling pointer, you get undefined behaviour. Of
course, undefined behaviour is not acceptable for Python.
In the case of release-reference, you nearly have that behaviour in
Python: When a function terminates, all its local variables are deleted,
and the objects decrefed. The only exception is an exception: a stack
frame in the traceback keeps the local variables alive even after the
end of the function.
There are two ways to work around this problem: a) don't assign
"interesting" objects to local variables, as done in the open-read
idiom, or b) unassign local variables in a try-finally-block. Of course,
if you have to write a try-finally-block, you could release the
underlying object right away also.
Enhancements in this area are possible, one might consider writing
transient foo = open(filename)
with the expectation that foo is decrefed when the scope is left even in
case of an exception. As with any language change, you need a really
good reason to implement it, though (and you need to think about
semantic subtleties, such as generators).
Regards,
Martin
More information about the Python-list
mailing list