[Tutor] finally

Steven D'Aprano steve at pearwood.info
Fri Jun 25 02:42:35 CEST 2010


On Fri, 25 Jun 2010 12:29:12 am Walter Prins wrote:
> On 24 June 2010 15:08, Christopher King <g.nius.ck at gmail.com> wrote:
> > so if you encounter an error that you won't handle, but you still
> > to close files and save data, you could use finally?
>
> More strongly, you *should* use finally, as there's no other way to
> ensure your cleanup code will run regardless of unpredictable
> exceptions that may be thrown...

Actually, no, having learned `finally`, you should not use it and use 
`with` instead! (For some definition of "should".)

Starting from Python 2.5, Python provides a new, more flexible and 
powerful mechanism for running cleanup code: the `with` statement.

In Python 2.5 you need to import it first:

from __future__ import with_statement

In Python 2.6 and higher you don't need the import.

Then you write something like this:

with open('myfile', 'w') as f:
    data = some_function()
    f.write(data)

and f will be automatically closed at the end of the with block even if 
some_function raises an exception.

Of course, writing your own cleanup code using try...finally will 
continue to be supported, and it's *not* wrong to use it (especially if 
you have to support versions of Python prior to 2.5) but the with 
statement is the preferred way to do it now.

See more information about it here:

http://effbot.org/zone/python-with-statement.htm



-- 
Steven D'Aprano


More information about the Tutor mailing list