Fast, Easy, Cheap: Pick One

Just some other blog about computers and programming

Easy Context Managers With Contextlib

Do you ever use some functions in Python that you wish had a context manager, but do not? Are you too lazy to write one? Then use the contextlib module!

I often need to work with gzipped files, but unfortunately gzip.open() doesn’t work as a context manger. Fortunately contextlib has a convenient closing() function that makes converting any file-like object to a context manager trivial. For example, previously where I had code like:

1
2
3
4
5
6
7
8
9
10
import gzip

# ...

try:
    f = gzip.open(path)
    do_stuff(f)
    # ...
finally:
    f.close()

I can now replace it with:

1
2
3
4
5
6
7
8
import gzip
from contextlib import closing

# ...

with closing(gzip.open(path)) as f:
    do_stuff(f)
    # ...

Apart from the closing() function, contextlib includes a few other convenient context manager building functions:

contextlib.contextmanager(func) can be used as a decorator to turn any function with a single yield in to a context manager.

contextlib.nested(m1, m2, ...) allows you to nest multiple context managers but has been superseded in Python 2.7 by the new with syntax.

contextlib is available as of Python 2.5