does python have useless destructors?

David Turner dkturner at
Thu Jun 10 10:00:09 CEST 2004

Peter Hansen <peter at> wrote in message news:<-oadnfu_sdwTUFrdRVn-hw at>...
> Michael P. Soulier wrote:
> I'll limit my response to point out that this code:
> > myfile = open("myfilepath", "w")
> > myfile.write(reallybigbuffer)
> > myfile.close()
> ... immediately raises a warning flag in the mind of an
> experienced Python programmer.
> This code, on the other hand:
> > try:
> >     myfile = open("myfilepath", "w")
> >     myfile.write(reallybigbuffer)
> > finally:
> >     myfile.close()
> ... "feels" just right.  This is how you do it when you
> want to be sure the file is closed, regardless of
> other considerations like garbage collection, etc.

Keeping track of all of the possible places where an exception may
occur can be extremely difficult.  Actually _catching_ all of those
exceptions often turns the code into "finally soup".  Furthermore,
it's not always myfile.close() -- many objects have cleanup semantics
that are not always obvious, particularly to someone who may be using
them for the first time.  Off the top of my head, an example of this
is DirectShow's filter graphs.

"Finally" can't be considered a good solution, in the light of better
solutions which are available: ruby closures, for example (with file
do...) and C++ RAII.  Both solve the same problem as finally, but far
more elegantly.  In fact, finally is only one step away from explicit
acquire/release cycles - the same malloc/free approach we were trying
to get away from, right?

> It is simple, clean, and most of all, very explicit.

I'd challenge you on all three of those.  Simple?  Not to the guy who
has to remember to write finally around every resource-allocating
operation that may raise an exception.  Clean?  Hardly.  See my
example below.  Explicit?  Yes, that's true, it is explicit.  Much in
the same way as malloc and free are explicit.  Are you sure that's
what you want?

Here are two code samples that do exactly the same thing, one in C++
and one in Python.  I would be very pleased to see the day when the
Python code is at least as neat as the C++ code.


mutex::scoped_lock lock(db_lock);

David Turner

More information about the Python-list mailing list