Skip to content

Instantly share code, notes, and snippets.

@michaelconnor00
Last active March 10, 2016 20:12
Show Gist options
  • Save michaelconnor00/498bee6af538de8758ea to your computer and use it in GitHub Desktop.
Save michaelconnor00/498bee6af538de8758ea to your computer and use it in GitHub Desktop.
from contextlib import contextmanager
@contextmanager
def tag(name):
print("<%s>" % name)
yield
print("</%s>" % name)
>>> with tag("h1"):
... print("foo")
...
<h1>
foo
</h1>
#############
# Using a 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()
""" OUTPUT
<p>
Here is some non-HTML
</p>
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment