Skip to content

Commit f7e60a6

Browse files
taleinatCarreau
andauthored
[2.7] bpo-33468: Add try-finally contextlib.contextmanager example (GH-7816) (GH-8427)
(cherry picked from commit bde782b) Co-authored-by: Matthias Bussonnier <[email protected]>
1 parent fbcb6fa commit f7e60a6

File tree

1 file changed

+18
-12
lines changed

1 file changed

+18
-12
lines changed

Doc/library/contextlib.rst

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -24,22 +24,28 @@ Functions provided:
2424
function for :keyword:`with` statement context managers, without needing to
2525
create a class or separate :meth:`__enter__` and :meth:`__exit__` methods.
2626

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

2934
from contextlib import contextmanager
3035

3136
@contextmanager
32-
def tag(name):
33-
print "<%s>" % name
34-
yield
35-
print "</%s>" % name
36-
37-
>>> with tag("h1"):
38-
... print "foo"
39-
...
40-
<h1>
41-
foo
42-
</h1>
37+
def managed_resource(*args, **kwds):
38+
# Code to acquire resource, e.g.:
39+
resource = acquire_resource(*args, **kwds)
40+
try:
41+
yield resource
42+
finally:
43+
# Code to release resource, e.g.:
44+
release_resource(resource)
45+
46+
>>> with managed_resource(timeout=3600) as resource:
47+
... # Resource is released at the end of this block,
48+
... # even if code in the block raises an exception
4349

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

0 commit comments

Comments
 (0)