...

/

Puzzle 20: Explanation

Puzzle 20: Explanation

Let’s learn how context managers work when using a with statement.

We'll cover the following...

Try it yourself

Try executing the code below to verify the results:

Press + to interact
class timer:
def __init__(self, name):
self.name = name
def __enter__(self):
...
def __exit__(self, exc_type, exc_value, traceback):
result = 'OK' if exc_type is None else 'ERROR'
print(f'{self.name} - {result}')
return True
with timer('div'):
1 / 0

Explanation

Most people expect to see a ZeroDivisionError exception in the output of the above code. The timer syntax in the code above is a context manager. A context manager is used with the with statement and is usually for managing resources. For example, the snippet with open('input.txt') will make sure that the file is closed after the code inside the ...