News for hackers. Stuff that matters.
Re:Exception Safety, Garbage Collection etc. (a.k.a. Why Doe... by MostAwesomeDude on Friday May 06, 2011 @12:34PM (#2521454)
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.

There are no comments on this comment yet.