What do blocks give you that good old-fashioned first-class functions don't?
with open('file') as myfile:
process(myfile.read())
When control leaves that context, `file.close()` is always called. You don't have to remember to close it. Even if `process()` raises an exception, the `with open` context will close it before passing the exception upward. You never have to remember to clean up the file yourself.It's not that you can't do all that without context managers, obviously. People have done it for a long time. It's just that the `with open...` pattern is effectively bulletproof and removes just one more potential footgun.
open('file', (myfile) => process(myfile.read()))
It would be on the implementer of `open` to call `file.close()`, but presumably that's true of python as well? def open_context_manager(filename):
try:
f = open(filename)
yield f
finally:
f.close()