which one of these is better?

John Salerno johnjsal at NOSPAMgmail.com
Thu Oct 26 16:50:49 EDT 2006


Fredrik Lundh wrote:

> This wasn't very difficult, was it?

Well when you put it that way, no! :)

But one thing that caught me up was what happens if the initial 
expression raises an exception? For example:

with open('file.txt'):
     #do stuff

If the file can't be opened for whatever reason, does __exit__ get 
called, or can it not get that far if the expression doesn't evaluate?

I guess my thinking was this: before the with statement came along, the 
idiom for opening files was something like this:

try:
     open('file.txt')
     #do stuff
except IOError:
     #more stuff
except OtherError:
     #yet more

and so forth (and all this was wrapped in a try/finally blocked to close 
the file, I think). But now that we can use the 'with' statement, it 
seems like the initial opening of the file (previously "checked" in the 
try block) is now just floating around and still requires a try block 
wrapped around it in case something goes wrong.



More information about the Python-list mailing list