Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/python/design_contextmanager.py
1240 views
1
"""
2
This is a simple example of a context manager. The context manager is
3
implemented by a decorator provided by the contextlib module.
4
5
You will see that tag will yield after the first print statement and as it a
6
contextmanager, it is resumed after the __exit__ call, which is called by
7
default when the with statement falls out of scope and in that case, the next
8
print statement is called.
9
10
This outputs:
11
<h1>
12
foo
13
</h1>
14
"""
15
16
from contextlib import contextmanager
17
18
@contextmanager
19
def tag(name):
20
print("<%s>" % name)
21
yield
22
print("</%s>" % name)
23
24
with tag("h1"):
25
print("foo")
26
27