Context Manager Class in Python
Level 5273 keystrokes
This implements a context manager class with __enter__ and __exit__ methods. The timer measures code execution time within the with block.
Python code
# Define context manager class for timing1class Timer: # __enter__ is called when entering with block2 def __enter__(self): # Import time locally inside the method3 import time # Record start time4 self.start = time.time() # Return self for use in with statement5 return self6 # __exit__ is called when exiting with block7 def __exit__(self, exc_type, exc_val, exc_tb): # Import time again (local imports are method-scoped)8 import time # Calculate elapsed time9 self.elapsed = time.time() - self.start # Print formatted elapsed time10 print(f"Elapsed: {self.elapsed:.4f}s") # Return False to propagate exceptions11 return False12 # Use timer with context manager13with Timer() as t: # Code to time - sum of range14 sum(range(100000))Output
Elapsed: 0.0012s
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
_× 11(× 8)× 8.× 7:× 6,× 3"× 2=× 2-× 1{× 1