does python have useless destructors?

Carl Banks imbosol at aerojockey.invalid
Sun Jun 13 11:32:58 CEST 2004

David Turner wrote:
> Well-defined destructor semantics have proven to be a robust,
> reliable, and surprisingly general solution to a wide range of
> problems. It wouldn't be *that* hard to implement them in Python - so
> why not adopt a good idea?

Wrong.  It would be almost impossible in Python.

Python can never rely on someone not taking a reference to your
resource-owning object.  Anyone can store an open file object in a
list, for example, and there might even be good reasons to do it.
Thus, you can never guarantee that the garbage collector will pick up
the object when the function exits, even if it were perfect.

OTOH, if you indiscreetly finalize (for example, calling close on a
file object) any resource-owning object as soon as the function that
created it exits, not waiting for garbage collector to pick it up,
then you've pretty much stepped on the toes of someone else 

It seems to me that you are failing to taking the possibility that
these thing can happen into account.  But, in Python, they can and do.
Finalizing an object as soon as the name binding it goes out of scope
is not always the right thing to do.

The fact is: when you open a file, or acquire a lock, or obtain any
other resource, you, the programmer, have to know whether you want
that resource released when the name bound to the object that owns the
resource goes out of scope or not.  The language can only guess; it
happens to guess "yes" in C++ and "no" in Python.  When the guess is
wrong, you have to tell the language.

Because of the above problems, "no" is the correct guess in Python.
Forcing the programmer to explicitly release resources (excepting
resources that don't require timely release, like RAM) is a lesser
evil than the two results above.

CARL BANKS            
"If you believe in yourself, drink your school, stay on drugs, and
don't do milk, you can get work." 
          -- Parody of Mr. T from a Robert Smigel Cartoon

More information about the Python-list mailing list