bpo-33468: Add try-finally contextlib.contextmanager example (GH-7816) · python/cpython@bde782b (original) (raw)

Original file line number Diff line number Diff line change
@@ -47,22 +47,28 @@ Functions and classes provided:
47 47 function for :keyword:`with` statement context managers, without needing to
48 48 create a class or separate :meth:`__enter__` and :meth:`__exit__` methods.
49 49
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 + An abstract example would be the following to ensure correct resource
55 + management::
51 56
52 57 from contextlib import contextmanager
53 58
54 59 @contextmanager
55 - def tag(name):
56 - print("<%s>" % name)
57 - yield
58 - print("</%s>" % name)
60 + def managed_resource(*args, **kwds):
61 + # Code to acquire resource, e.g.:
62 + resource = acquire_resource(*args, **kwds)
63 + try:
64 + yield resource
65 + finally:
66 + # Code to release resource, e.g.:
67 + release_resource(resource)
59 68
60 - >>> with tag("h1"):
61 - ... print("foo")
62 - ...
63 -

64 - foo
65 -
69 + >>> with managed_resource(timeout=3600) as resource:
70 + ... # Resource is released at the end of this block,
71 + ... # even if code in the block raises an exception
66 72
67 73 The function being decorated must return a :term:`generator`-iterator when
68 74 called. This iterator must yield exactly one value, which will be bound to