First page Back Continue Last page Overview Graphics

Composition of Context Managers

from contextlib import contextmanager

@contextmanager

def tag(name):

print("<%s>" % name)

yield

print("</%s>" % name)

with tag("body") as r:

with tag("p") as s:

print("Some text!")

# equivalent to

with tag("body") as r, tag("p") as s:

print("Just some text!")