Class destructors

Alex Martelli aleaxit at yahoo.com
Wed Jun 20 08:50:54 EDT 2001


"Graham Ashton" <graham at coms.com> wrote in message
news:Se_X6.1458$h45.9288 at news.uk.colt.net...
> I understand that Python doesn't have the equivalent of the DESTROY()
> method in Perl, as the tutorial says:
>
>   "There are no special constructors or destructors."
>
> Surely there is a way of executing some code before the garbage collector
> destroys the object though? Can anybody give me some pointers?

Special method __del__, already mentioned by several respondants, is
really a finalizer, rather than a destructor.  In the current version of
Python, o.__del__() will be called when AND if o's refcount drops to
0 -- but it's *NOT* a language guarantee.  If o is in a reference cycle,
the whole cycle becomes un-garbage-collectable due to o.__del__'s
existence.  In other Python implementations (Jython, Python.NET, and
possibly future Classic-Python implementations too), finalization might
happen later, possibly MUCH later, than o becoming unreachable -- in
other words, exactly as for any other language in a JVM or .NET world.

I know it sounds unwieldy to people used to C++'s destructors (and in
particular the nice way they work for objects of storage class auto), but
there are good reasons for this.  And Java's success shows it's anything
but impossible to program WITHOUT relying on certainty of finalizers
getting called.  When you DO need to ensure finalization, well, that's
what try/finally is for, in both Python and Java.


> Specifically, I want to close a socket when I've finished with my object
> without having to do so explicitly from with the program that uses the
> object.

Explicit is better than implicit.  Use a try/finally.  One day you'll
be happy you did!-)


Alex






More information about the Python-list mailing list