No destructor

Alex Martelli alex at magenta.com
Tue Aug 22 04:12:09 EDT 2000


"Pete Shinners" <pete at visionart.com> wrote in message
news:8ns4mu$9c4$1 at la-mail4.digilink.net...
>
> "Makhno" <mak at imakhno.freeserve.co.uk> wrote
> > >I'm fairly new to Python, so apologies if this has cropped up before.
As
> I
> > >understand it, there is no destructor/finalise in Python.  What was the
> > >reason behind this omission?
> >
> > The method is called __del__
>
> be aware that there are cases where the destructor will never
> be called. i can't remember what they are (don't have my book
> in front of me). but i do remember reading they weren't
> guaranteed to be called, and there were a couple of cases.

I believe that, besides circular references, you may have in
mind the fact that __del__ may not be called for objects still
alive at program's end, also depending on HOW the program itself
terminates.  Python makes a best-effort to call destructors,
but only if the termination of the process is reasonably
'normal' -- os._exit() is specifically designed for "emergency
exits", as fast as possible, no clean-ups, etc, etc.

The situation is pretty similar to C++'s destructors, by the
way.  If, in C++, you allocate something with new, and never
free it with delete, its destructor is not going to be called;
Python is more accurate than this in calling destructors, most
of the time.  Java's finalize is even less reliable -- it's
QUITE likely that objects may not get finalized, depending on
circumstances of termination &tc.


> because of this i've never been able to let myself rely on
> the __del__ destructor. (will it be called???) will the new
> garbage cleanup in 2.0 fix this problem?

GC and reliable-finalization never seem to cooperate 100% in
any language or environment I know of.  Sure, with GC, circular
references will not mean automatic resource leaks, which is
no doubt a gain, but, consider for example -- in WHAT order
would the objects' __del__ methods be called?  I know of no
way to ensure a good result.

If you need 100% reliable finalization, try/finally is the
only absolutely ironclad way.  Well, ALMOST absolutely: I
think an os._exit() will still manage to mess things up!-)


Alex






More information about the Python-list mailing list