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 manager1class Timer: # __enter__ runs when the with block starts2 def __enter__(self): # Import time inside the method (usually done at the top of the file)3 import time # Record the start time in seconds4 self.start = time.time() # Return self (bound to the variable after as, if one is given)5 return self6 # __exit__ runs when the block ends; *args receives exception info7 def __exit__(self, *args): # Import time again: the earlier import was local to __enter__8 import time # Print the elapsed time with 4 decimal places9 print(f"Elapsed: {time.time() - self.start:.4f}s")10 # Enter the with block: __enter__ is called first11with 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. 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