Context Manager Protocol in Python

Level 4207 keystrokes

This implements context manager protocol with __enter__ and __exit__. It allows using the class with the with statement.

Python code

# Define a class that works as a context manager
1class Timer:
# __enter__ runs when the with block starts
2 def __enter__(self):
# Import time inside the method (usually done at the top of the file)
3 import time
# Record the start time in seconds
4 self.start = time.time()
# Return self (bound to the variable after as, if one is given)
5 return self
6
# __exit__ runs when the block ends; *args receives exception info
7 def __exit__(self, *args):
# Import time again: the earlier import was local to __enter__
8 import time
# Print the elapsed time with 4 decimal places
9 print(f"Elapsed: {time.time() - self.start:.4f}s")
10
# Enter the with block: __enter__ is called first
11with Timer():
# The work being timed: sum of 0 to 99999 (the result is discarded)
12 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.

  • _× 8
  • (× 8
  • )× 8
  • :× 6
  • .× 5
  • "× 2
  • -× 1
  • ,× 1
  • {× 1
  • }× 1

More Python examples at level 4

← Python typing practice