Destructors

Robert Oschler Oschler at earthlink.net
Sat Apr 6 05:31:20 EST 2002


My favorite object construct/destruct paradigm is the Boost Library's
shared_ptr template class for C++ objects.  When the reference count of the
shared pointer reaches zero, the destructor of the object it wraps is
called.  Delphi has "interfaces" which do the same, although they behave
differently than classes do when it comes to inheritance and other subtle
programming aspects so it can be a little awkward at times.

Python seems to follow the Java finalize/gc() model where destructors (or
finalize() in Java) aren't called until the garbage collector frees the
object.  As in Java, the Python book I'm reading stresses that you have no
idea when the destructor will be called, or if it will happen at all.  Just
like the Java books I have, the Python book recommends creating a method,
for example close(), to be called explicitly, probably in a finally portion
of a try/finally block.  So of course you have to remember, for every class
that needs to immediately free a resource when the class object refcount
reaches 0,  to pair each such class instance creation with a call to the
custom "close()" method and wrap the code in a try/finally block.

Is there a way to achieve the same functionality as the shared_ptr template
class (stack-based refcounted object) in Python?  If not, is there a place
to post a language feature suggestion for discussion and possible review by
the Python Illuminati?

thx

















More information about the Python-list mailing list