Context Manager in Python

Level 4151 keystrokes

This creates a context manager class with __enter__ and __exit__ methods for use with the with statement.

Python code

# Context manager class (a simplified timer that stores fixed values)
1class Timer:
# __enter__ runs when the with block starts
2 def __enter__(self):
# Set start (a placeholder 0 instead of a real time)
3 self.start = 0
# Return self; "as t" binds it to t
4 return self
5
# __exit__ runs when the with block ends
6 def __exit__(self, *args):
# Set end to 1
7 self.end = 1
8
# Enter the block; t is the object returned by __enter__
9with Timer() as t:
# Runs inside the block: prints Running
10 print("Running")
# After the block __exit__ has run, so t.end is 1
11print(t.end)

Output

Running
1
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
  • (× 5
  • )× 5
  • :× 4
  • .× 3
  • "× 2
  • =× 2
  • ,× 1
  • *× 1

More Python examples at level 4

← Python typing practice