does python have useless destructors?

Michael Geary Mike at DeleteThis.Geary.com
Wed Jun 9 23:52:27 EDT 2004


Peter Hansen 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.

And it has a bug. :-)

What if "myfilepath" is not writable? The open() call raises an exception,
which jumps to the finally: block, where myfile.close() fails because myfile
is undefined.

What would be the cleanest way to code this to handle that error situation?

-Mike





More information about the Python-list mailing list