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

Original file line numberDiff line numberDiff line change

@@ -47,22 +47,28 @@ 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+

An abstract example would be the following to ensure correct resource

55+

management::

5156
5257

from contextlib import contextmanager

5358
5459

@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)

5968
60-

>>> with tag("h1"):

61-

... print("foo")

62-

...

63-

<h1>

64-

foo

65-

</h1>

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

6672
6773

The function being decorated must return a :term:`generator`-iterator when

6874

called. This iterator must yield exactly one value, which will be bound to