Last active
March 10, 2016 20:12
-
-
Save michaelconnor00/498bee6af538de8758ea to your computer and use it in GitHub Desktop.
Context manager fun stuff From http://jeffknupp.com/blog/2016/03/07/python-with-context-managers/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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