[Python-ideas] with statement vs. try...except...finally

Pascal Chambon chambon.pascal at wanadoo.fr
Fri May 29 21:49:31 CEST 2009


Gerald Britton a écrit :
> I'm wondering if the "with" statement should have exception clauses
> like the "try" statement, even though this seems to defeat part of the
> reason for the "with" statement.
>
> Currently I have a program segment that opens a file and reads a line,
> something like this (distilled to its elements for illustration):
>
> try:
>     f = open('foo')
>     line = f.readline()
>     f.close()
> except IOError:
>     line = 'default'
>
> So that I get a default value if anything goes awry whilst reading the file.
>
> If I write it using a "with" statement, I might have:
>
> line = 'default'
> with open('foo') as f:
>    line = f.readline()
>
> Fine so far, but what if I want to be more granular?  e.g. with "try...except":
>
> try:
>     f = open('foo')
> except IOError:
>     line = "can't open"
>
> try:
>     line = f.readline()
> except IOError:
>     line = "can't read"
>
> try:
>     f.close()
> except IOError:
>     line = "can't close"
>
> I can't see how to replace the above try-triplet with a "with"
> encapsulation. Or, do I have to wrap the "with" statement in try like
> this:
>
> try:
>
>   with open('foo') as f:
>      line = f.readline()
>
> except IOError:
>   line = 'problem with read or close"
>
>
>   
I'd say the triplet of "try...except" clauses above isn't OK, because if 
the file opening fails, teh code will try anyway to read it and to close 
it, leading to nameError and other uncaught exception.

But the last clause, wrapped in try..except, seems fine to me.

++
Pascal






More information about the Python-ideas mailing list