Puzzle 20 A Divided Time

Python Brain Teasers — by Miki Tebeka (29 / 40)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 TF (Without IDF) | TOC | Tell Me the Future 👉

timer.py

​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.

images/hline.png

This code will print: div — ERROR

images/hline.png

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.

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.