[Python-ideas] Extending error handling on with statements.

Nick Coghlan ncoghlan at gmail.com
Mon Mar 28 05:09:20 CEST 2011

On Mon, Mar 28, 2011 at 7:33 AM, Jakob Bowyer <jkbbwr at gmail.com> wrote:
> I personally love using with statements when handling file like objects.
> This is all well and good until an exception is thrown from the with
> statement. This is ok if you expect the exception because you can use try
> and except but personally I feel that another condition to with would feel
> more 'pythonic' this means that you could fail the with statement with an
> exception jump to the clause, then jump back to the with statement trying
> the code in the clause e.g. rather than
> try:
>     with open('nofile.txt','r') as inp:
>         #nofile.txt does not exist and throws an exception
> except IOError:
>     with open('another.txt','r') as inp:
>         #carry on where you left off...
> You could simply have
> with open('nofile.txt','r') as inp:
>     #exception here
> else:
>     #give a new file to the with statement here and/or run some panic code

Don't fight the language, just write a new CM that does what you want:

with open_any('r', 'nofile.txt', 'another.txt') as inp:
    # If we get here, one of the files was opened
    # We can use inp.name to find out which one

(And open_any() is pretty easy to write as a generator with an initial
loop containing a try/catch block, an else clause on the loop that
throws an exception, and then a subsequent with statement that yields
the open file)

You *really* need to be careful when wrapping try blocks around with
statements, as they're almost always too broad (typically, you only
want to cover the CM creation, not the entire body of the with


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list