summaryrefslogtreecommitdiff
path: root/Doc
diff options
context:
space:
mode:
authorTal Einat <taleinat+github@gmail.com>2018-07-24 00:38:34 +0300
committerGitHub <noreply@github.com>2018-07-24 00:38:34 +0300
commitf7e60a69485097dc28f000c55615038278f84333 (patch)
tree4197343de55aadf9325e93d3c0aec9736109aea0 /Doc
parentfbcb6fae6233efbde1f6bb9fe51e33baec4767b8 (diff)
downloadcpython-git-f7e60a69485097dc28f000c55615038278f84333.tar.gz
[2.7] bpo-33468: Add try-finally contextlib.contextmanager example (GH-7816) (GH-8427)
(cherry picked from commit bde782bb594edffeabe978abeee2b7082ab9bc2a) Co-authored-by: Matthias Bussonnier <bussonniermatthias@gmail.com>
Diffstat (limited to 'Doc')
-rw-r--r--Doc/library/contextlib.rst30
1 files changed, 18 insertions, 12 deletions
diff --git a/Doc/library/contextlib.rst b/Doc/library/contextlib.rst
index c88dd2318b..183da70603 100644
--- a/Doc/library/contextlib.rst
+++ b/Doc/library/contextlib.rst
@@ -24,22 +24,28 @@ Functions provided:
function for :keyword:`with` statement context managers, without needing to
create a class or separate :meth:`__enter__` and :meth:`__exit__` methods.
- A simple example (this is not recommended as a real way of generating HTML!)::
+ While many objects natively support use in with statements, sometimes a
+ resource needs to be managed that isn't a context manager in its own right,
+ and doesn't implement a ``close()`` method for use with ``contextlib.closing``
+
+ An abstract example would be the following to ensure correct resource
+ management::
from contextlib import contextmanager
@contextmanager
- def tag(name):
- print "<%s>" % name
- yield
- print "</%s>" % name
-
- >>> with tag("h1"):
- ... print "foo"
- ...
- <h1>
- foo
- </h1>
+ def managed_resource(*args, **kwds):
+ # Code to acquire resource, e.g.:
+ resource = acquire_resource(*args, **kwds)
+ try:
+ yield resource
+ finally:
+ # Code to release resource, e.g.:
+ release_resource(resource)
+
+ >>> with managed_resource(timeout=3600) as resource:
+ ... # Resource is released at the end of this block,
+ ... # even if code in the block raises an exception
The function being decorated must return a :term:`generator`-iterator when
called. This iterator must yield exactly one value, which will be bound to