does python have useless destructors?

Hannu Kankaanp?? hanzspam at yahoo.com.au
Thu Jun 10 03:18:13 EDT 2004


Peter Hansen <peter at engcorp.com> wrote in message news:<-oadnfu_sdwTUFrdRVn-hw at powergate.ca>...
> 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.

It's not that simple when you compare it to C++ RAII idiom,
and the above code is actually wrong. If open() raises an
exception, myfile hasn't yet been assigned and myfile.close()
will raise another, unwanted exception of type "NameError".
The correct idiom is:

myfile = file("myfilepath", "w")
try:
    myfile.write(reallybigbuffer)
finally:
    myfile.close()

I'd very much prefer something simpler that leaves no room
for errors, e.g.

with myfile = file("myfilepath", "w"):
    myfile.write(reallybigbuffer)

(this, and more generic solutions with code blocks have been
suggested here many times)



More information about the Python-list mailing list