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

Jakob Bowyer jkbbwr at gmail.com
Sun Mar 27 23:33:52 CEST 2011

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

    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
    #give a new file to the with statement here and/or run some panic code
where your program does something to fix the situation.

It could be a foolish idea as I am only a intermediate user but I thought it
might be worth voicing none the less as you don't learn from staying silent.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110327/7532810d/attachment.html>

More information about the Python-ideas mailing list