Just to give an example where this would be redundant, use contextlib, which is more for use with generators:
Here is a good and useful example of a context manager. I found it on David Basley's blog:
http://dabeaz.blogspot.de/2010/02/context-manager-for-timing-benchmarks.html
and modified it a bit to use the best timer on the platform, the trick I use from the timeit module:
# benchmark.py import timeit class benchmark(object): from timeit import default_timer as timer def __init__(self, name): self.name = name def __enter__(self): self.start = self.timer() def __exit__(self, ty, val, tb): end = self.timer() print("%s : %0.3f seconds" % (self.name, end-self.start)) return False
Now this gives you a context manager that you can use as follows:
with benchmark('algorithm 1'): ... (some computation) with benchmark('other approach'): ... (some other computation)
and you will get a printout. I liked this example and would like to share it.
source share