from contextlib import contextmanager @contextmanager def tag(name): print "<%s>" % name yield print "</%s>" % name with tag("h1"): print "foo" """ <h1> foo </h1> """
@contextlib.contextmanager def manager(*args): object = initialize(args) try: yield object finally: # cleanup object.close()
[0] http://docs.python.org/2/reference/datamodel.html