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

Carl Johnson cmjohnson.mailinglist at gmail.com
Sat May 30 00:02:31 CEST 2009


This example is too simplified to understand if it's worth adding an
except clause or not. If all you're doing is pulling the text out of
the file, why can't you just make a function for this?

lines = fancyread("myfile.txt") #Returns "couldn't open", "couldn't
close", etc. in case of errors

The point of the with statement is that your want to do more
sophisticated stuff with the file contents, but still want the file
closed at the end. But if you're doing more sophisticated stuff, it's
not clear that you'd suddenly want to have "can't close" substituted
in for whatever it was you whipped up by processing the file contents.

So, I think we need a better example before we can judge the merits of
an except clause.

There's also the question of what the except clause would apply to.
There are three places where a "with" could throw an exception:

with open("myfile") as f: #Could barf on opening
     f.read() #Could barf in processing
#Could barf during clean up

Which of the three spots will the except clause deal with? All of
them? As it is, barfing in the middle is already given to the context
manager to clean up (though the context manager could always throw its
own error during its own clean up), so it would be weird to have any
other custom clean up that went in addition to what the context
manager is already doing.

-- Carl



More information about the Python-ideas mailing list