4 ms·
What do blocks give you that good old-fashioned first-class functions don't?
by akavi 3y ago
What do blocks give you that good old-fashioned first-class functions don't?
- kstrauser 3y agoFor example, here's how you'd read a file in Python and operate on its contents. 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.
- akavi 3y agoIn JS, we could do: 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?
- kstrauser 3y agoI think so, depending on how I'm reading your definition of "the implementer". If you meant "the code that implements the open() context manager", then yes. It looks something like: def open_context_manager(filename): try: f = open(filename) yield f finally: f.close()