Puzzle 20 A Divided Time
Python Brain Teasers — by Miki Tebeka (29 / 40)
👈 TF (Without IDF) | TOC | Tell Me the Future 👉
1: class timer:
- def __init__(self, name):
- self.name = name
-
5: def __enter__(self):
- ...
-
- def __exit__(self, exc_type, exc_value, traceback):
- result = 'OK' if exc_type is None else 'ERROR'
10: print(f'{self.name} - {result}')
- return True
-
-
- with timer('div'):
15: 1 / 0
Guess the Output
IMPORTANT
Try to guess what the output is before moving to the next page.
This code will print: div — ERROR
You might have expected to see a ZeroDivisionError exception.
timer is a context manager. A context manager is used with the with statement and is usually for managing resources. For example, with open(’input.txt’) will make sure that the file is closed after the code inside the context manager is done, even if the code inside the with raised an exception.