From https://jeffknupp.com/blog/2016/03/07/python-with-context-managers/. Can be used both as context manager and as function decorator.
from contextlib import ContextDecorator
class makeparagraph(ContextDecorator):
def __enter__(self):
print('<p>')
return self
def __exit__(self, *exc):
print('</p>')
return False
@makeparagraph()
def emit_html():
print('Here is some non-HTML')
emit_html()