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 manager1class Timer: # __enter__ is called when entering the 'with' block2 def __enter__(self):3 print("Start") # Return value is assigned to variable after 'as' (if used)4 return self5 # __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 called9with Timer(): # This code runs between __enter__ and __exit__10 print("Working")Output
Start Working End
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