Skip to content

Commit 5b3643d

Browse files
miss-islingtonCarreau
authored andcommitted
bpo-33468: Add try-finally contextlib.contextmanager example (GH-7816) (GH-8426)
(cherry picked from commit bde782b) Co-authored-by: Matthias Bussonnier <[email protected]>
1 parent 1127849 commit 5b3643d

File tree

1 file changed

+17
-11
lines changed

1 file changed

+17
-11
lines changed

Doc/library/contextlib.rst

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -36,22 +36,28 @@ Functions and classes provided:
3636
function for :keyword:`with` statement context managers, without needing to
3737
create a class or separate :meth:`__enter__` and :meth:`__exit__` methods.
3838

39-
A simple example (this is not recommended as a real way of generating HTML!)::
39+
While many objects natively support use in with statements, sometimes a
40+
resource needs to be managed that isn't a context manager in its own right,
41+
and doesn't implement a ``close()`` method for use with ``contextlib.closing``
42+
43+
An abstract example would be the following to ensure correct resource
44+
management::
4045

4146
from contextlib import contextmanager
4247

4348
@contextmanager
44-
def tag(name):
45-
print("<%s>" % name)
46-
yield
47-
print("</%s>" % name)
49+
def managed_resource(*args, **kwds):
50+
# Code to acquire resource, e.g.:
51+
resource = acquire_resource(*args, **kwds)
52+
try:
53+
yield resource
54+
finally:
55+
# Code to release resource, e.g.:
56+
release_resource(resource)
4857

49-
>>> with tag("h1"):
50-
... print("foo")
51-
...
52-
<h1>
53-
foo
54-
</h1>
58+
>>> with managed_resource(timeout=3600) as resource:
59+
... # Resource is released at the end of this block,
60+
... # even if code in the block raises an exception
5561

5662
The function being decorated must return a :term:`generator`-iterator when
5763
called. This iterator must yield exactly one value, which will be bound to

0 commit comments

Comments
 (0)