Great explanation from @Martijn Pieters. Since yield is redundant in your case, you can achieve the same by creating your own context manager (without yield and contextlib.contextmanager ). It is simpler and more understandable. So in your case, you can implement something as follows.
import time class time_print(object): def __init__(self, task_name): self.task_name = task_name def __enter__(self): self.t = time.time() def __exit__(self): print self.task_name, "took", time.time() - self.t, "seconds." def doproc(): x=1+1 with time_print("processes"):
Internally, contextlib.contextmanager calls these magic functions __enter__ and __exit__, as explained by @Martijun Pieters. Hope this helps!
source share