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 timing
1class Timer:
# __enter__ is called when entering with block
2 def __enter__(self):
# Import time locally inside the method
3 import time
# Record start time
4 self.start = time.time()
# Return self for use in with statement
5 return self
6
# __exit__ is called when exiting with block
7 def __exit__(self, exc_type, exc_val, exc_tb):
# Import time again (local imports are method-scoped)
8 import time
# Calculate elapsed time
9 self.elapsed = time.time() - self.start
# Print formatted elapsed time
10 print(f"Elapsed: {self.elapsed:.4f}s")
# Return False to propagate exceptions
11 return False
12
# Use timer with context manager
13with Timer() as t:
# Code to time - sum of range
14 sum(range(100000))

Output

Elapsed: 0.0012s
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.

  • _× 11
  • (× 8
  • )× 8
  • .× 7
  • :× 6
  • ,× 3
  • "× 2
  • =× 2
  • -× 1
  • {× 1

More Python examples at level 5

← Python typing practice