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 generators
1from contextlib import contextmanager
# Import time for measuring elapsed time
2import time
3
# @contextmanager converts generator to context manager
# Function must yield exactly once
4@contextmanager
# timer is the context manager function
# label identifies what is being timed
5def timer(label: str):
# Record start time before entering with block
6 start = time.time()
# Print message when entering context
7 print(f"Starting {label}")
# try/finally ensures cleanup runs even if error occurs
8 try:
# yield pauses here and enters with block
# Code inside 'with' runs at this point
9 yield
10 finally:
# Calculate elapsed time after with block exits
11 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 first
14with timer("calculation"):
# This code runs where yield pauses
15 result = sum(range(1000000))
# Print the calculation result
16 print(f"Result: {result}")

Output

Starting calculation
Result: 499999500000
calculation took 0.0234s
Practice typing this code

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

More Python examples at level 5

← Python typing practice