does python have useless destructors?

Peter Hansen peter at engcorp.com
Wed Jun 9 22:55:08 EDT 2004


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.

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

-Peter



More information about the Python-list mailing list