Context Manager with contextlib in Python
Level 5308 keystrokes
This creates a context manager using @contextmanager decorator. The yield statement separates setup from cleanup code.
Python code
# Import contextmanager decorator from contextlib# Allows creating context managers from generators1from contextlib import contextmanager# Import time for measuring elapsed time2import time3 # @contextmanager converts generator to context manager# Function must yield exactly once4@contextmanager# timer is the context manager function# label identifies what is being timed5def timer(label: str): # Record start time before entering with block6 start = time.time() # Print message when entering context7 print(f"Starting {label}") # try/finally ensures cleanup runs even if error occurs8 try: # yield pauses here and enters with block # Code inside 'with' runs at this point9 yield10 finally: # Calculate elapsed time after with block exits11 elapsed = time.time() - start # Print timing result (always runs due to finally)12 print(f"{label} took {elapsed:.4f}s")13 # 'with timer(...)' enters context manager# "Starting calculation" prints first14with timer("calculation"): # This code runs where yield pauses15 result = sum(range(1000000)) # Print the calculation result16 print(f"Result: {result}")Output
Starting calculation Result: 499999500000 calculation took 0.0234s
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.
(× 9)× 9"× 8:× 7{× 4}× 4.× 3=× 3-× 1@× 1