Don’t do this:

thing = Thing()try: thing.do\_stuff()finally: thing.close() Do do this:

from contextlib import closingwith closing(Thing()) as thing: thing.do\_stuff() Why is the second better? Using contextlib.closing() ties closing the item to its creation. These baby examples are about equally easy to reason about, with only a single line in the try block, but consider what happens ~~if~~when more lines get added in future? In the first example, the close moves away, potentially offscreen, but that doesn’t happen in the second.