Finally, we present the third method. It serves to show another application of a context manager. We first construct a context manager object for measuring the elapsed time as shown:
import time class Timer: def __enter__(self): self.start = time.time() # return self def __exit__(self, ty, val, tb): end = time.time() self.elapsed=end-self.start print(f'Time elapsed {self.elapsed} seconds')
return False
Recall that the __enter__ and __exit__ methods make this class a context manager. The __exit__ method's parameters ty, val, and tb are in the normal case None. If an exception is raised during execution, they take the exception type, its value, and traceback information. The return value False indicates that the exception has not been caught so far.
We'll now show the use of the ...