Context Manager in Python

Level 4133 keystrokes

This creates a context manager for use with 'with' statements. __enter__ runs at start, __exit__ runs at end automatically.

Python code

# Define a class that can be used as a context manager
1class Timer:
# __enter__ is called when entering the 'with' block
2 def __enter__(self):
3 print("Start")
# Return value is assigned to variable after 'as' (if used)
4 return self
5
# __exit__ is called when leaving the 'with' block
# *args captures exception info (type, value, traceback)
6 def __exit__(self, *args):
7 print("End")
8
# 'with' statement ensures __enter__ and __exit__ are called
9with Timer():
# This code runs between __enter__ and __exit__
10 print("Working")

Output

Start
Working
End
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
  • "× 6
  • (× 6
  • )× 6
  • :× 4
  • ,× 1
  • *× 1

More Python examples at level 4

← Python typing practice