Writing a class with __enter__ and __exit__ for every small job is more ceremony than most jobs deserve. The contextlib module in the standard library has a shorter way: a generator with one yield, wrapped in a decorator. It also supplies ready-made managers for the situations that come up most. This lesson shows both, and ends with the habits of managing resources well.
More lessons in Complete Python Programming