__Enter__
or __exit__
seems to be difficult ...By using the contextmanager decorator, you can write relatively easily and with a feeling similar to a ruby block.
This is an example of the reference link
from contextlib import contextmanager
@contextmanager
def tag(name):
print "<%s>" % name
yield
print "</%s>" % name
>>> with tag("h1"):
... print "foo"
...
<h1>
foo
</h1>
It is like this.
http://docs.python.jp/2/library/contextlib.html#module-contextlib
Recommended Posts