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

Gerald Britton gerald.britton at gmail.com
Fri May 29 20:18:10 CEST 2009


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"


-- 
Gerald Britton



More information about the Python-ideas mailing list