import contextlib
# @contextlib.contextmanager
# def tag(name):
# print('<{}>'.format(name))
# yield
# print('</{}>'.format(name))
class tag(contextlib.ContextDecorator):
def __init__(self, name):
self.name = name
self.start_tag = '<{}>'.format(name)
self.end_tag = '</{}>'.format(name)
def __enter__(self):
print(self.start_tag)
def __exit__(self, exc_type, exc_val, exc_tb):
print(exc_type)
print(exc_val)
print(exc_tb)
print(self.end_tag)
with tag('h2'):
raise Exception('error')
print('test')
実行結果:
h2>
<class 'Exception'>
error
<traceback object at 0x7fa12715e0f0>
</h2>
Traceback (most recent call last):
File "/Users/hamazakiisao/PycharmProjects/python_programming/lesson.py", line 27, in <module>
raise Exception('error')
Exception: error