File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -36,22 +36,28 @@ Functions and classes provided:
3636 function for :keyword: `with ` statement context managers, without needing to
3737 create a class or separate :meth: `__enter__ ` and :meth: `__exit__ ` methods.
3838
39- A simple example (this is not recommended as a real way of generating HTML!)::
39+ While many objects natively support use in with statements, sometimes a
40+ resource needs to be managed that isn't a context manager in its own right,
41+ and doesn't implement a ``close() `` method for use with ``contextlib.closing ``
42+
43+ An abstract example would be the following to ensure correct resource
44+ management::
4045
4146 from contextlib import contextmanager
4247
4348 @contextmanager
44- def tag(name):
45- print("<%s>" % name)
46- yield
47- print("</%s>" % name)
49+ def managed_resource(*args, **kwds):
50+ # Code to acquire resource, e.g.:
51+ resource = acquire_resource(*args, **kwds)
52+ try:
53+ yield resource
54+ finally:
55+ # Code to release resource, e.g.:
56+ release_resource(resource)
4857
49- >>> with tag("h1"):
50- ... print("foo")
51- ...
52- <h1>
53- foo
54- </h1>
58+ >>> with managed_resource(timeout=3600) as resource:
59+ ... # Resource is released at the end of this block,
60+ ... # even if code in the block raises an exception
5561
5662 The function being decorated must return a :term: `generator `-iterator when
5763 called. This iterator must yield exactly one value, which will be bound to
You can’t perform that action at this time.
0 commit comments