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 |
|
I can now replace it with:
1 2 3 4 5 6 7 8 |
|
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