class Logger(object):
def __init__(self, i):
self.msgs = []
self.id = i
def __enter__(self):
print('BEGIN', self.id)
return self.msgs
def __exit__(self, exc_type, exc_value, traceback):
print('END', self.id, exc_type, exc_value, traceback)
for msg in self.msgs:
print('NOTE', self.id, msg)
return exc_type is ZeroDivisionError
for i in range(3):
print('----')
try:
with Logger(i) as log:
log.append('message {}'.format(i))
assert 3 % i == 0
except:
print('Caught', i)
Item 10: with Statement
Posted by Logan Chien