I got that the with
statement help you to turn this:
try:
f = open(my_file)
do_stuff_that_fails()
except:
pass
finally:
f.close()
Into:
with open(my_file) as f:
do_stuff_that_fails()
But how is that better? You still have to handle the case with the file not being able to be opened (like prompting the user to tell him he doesn't have permissions), so in reality you'd have:
try:
with open(my_file) as f:
do_stuff_that_fails()
except (IOError, OSError, Failure) as e:
do_stuff_when_it_doesnt_work()
Which is equivalent to:
try:
f = open(my_file)
do_stuff_that_fails()
except (IOError, OSError, Faillure) as e:
do_stuff_when_it_doesnt_work()
finally:
f.close()
Yes, you gained two lines, but you added a level of nesting which doesn't make it easier to read. Is the purpose of the with
statement to save you two lines or am I missing something?
It seems a lot to add a keyword just for that, so I feel like there is some syntax to handle the additional try/except that I don't know about.