Hacker News new | ask | show | jobs
by DanWaterworth 5517 days ago
And in python you'd use the with construct.
1 comments

To expand on this a bit:

  with open("some.filename") as f:
   ...
f is an opened file which is automatically closed. This isn't strictly necessary in Python, since files are flushed and closed when reaped, including in case of exception, but it's useful. You can also do this with all of the threading primitives:

  with threading.Lock():
   do_that_one_contentious_thing()
Useless syntactic sugar? Maybe. It's an explicit scope which makes certain guarantees, though, so it's not just fluff.

What was his other example? DB connections? Well, in Python, the DB API requires that DB connections not easily leak, but if you're stuck with a crappy driver, you can still auto-close your connections:

  with contextlib.closing(dbapi.Connection(...)) as handle:
   cursor = handle.cursor()
   ...
So it's definitely possible.

I think it's unfair of him to pick on Ruby and Python just because their syntax is more oriented towards assuming the garbage collector is non-sucky and exceptions aren't expensive.

Edit: Fixed formatting.