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 starts2 def __enter__(self): # Set start (a placeholder 0 instead of a real time)3 self.start = 0 # Return self; "as t" binds it to t4 return self5 # __exit__ runs when the with block ends6 def __exit__(self, *args): # Set end to 17 self.end = 18 # Enter the block; t is the object returned by __enter__9with Timer() as t: # Runs inside the block: prints Running10 print("Running")# After the block __exit__ has run, so t.end is 111print(t.end)Output
Running 1
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