Skip to content

Commit 9ab8fca

Browse files
committed
bpo-33468: Add try-finally contextlib.contextmanager example
This increase the chances of people following this example properly cleaning up resources.
1 parent 9bb9223 commit 9ab8fca

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

Doc/library/contextlib.rst

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -47,22 +47,27 @@ Functions and classes provided:
4747
function for :keyword:`with` statement context managers, without needing to
4848
create a class or separate :meth:`__enter__` and :meth:`__exit__` methods.
4949

50-
A simple example (this is not recommended as a real way of generating HTML!)::
50+
While many objects natively support use in with statements, sometimes a
51+
resource needs to be managed that isn't a context manager in its own right,
52+
and doesn't implement a ``close()`` method for use with ``contextlib.closing``
53+
54+
A example thus would be the following to ensure correct resource management::
5155

5256
from contextlib import contextmanager
5357

5458
@contextmanager
55-
def tag(name):
56-
print("<%s>" % name)
57-
yield
58-
print("</%s>" % name)
59+
def managed_resource(*args, **kwds):
60+
# Code to acquire resource, e.g.:
61+
resource = acquire_resource(*args, **kwds)
62+
try:
63+
yield resource
64+
finally:
65+
# Code to release resource, e.g.:
66+
release_resource(resource)
5967

60-
>>> with tag("h1"):
61-
... print("foo")
62-
...
63-
<h1>
64-
foo
65-
</h1>
68+
>>> with managed_resource(timeout=3600) as resource:
69+
... # Resource is released at the end of this block,
70+
... # even if code in the block raises an exception
6671

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

0 commit comments

Comments
 (0)