File tree Expand file tree Collapse file tree 1 file changed +16
-11
lines changed Expand file tree Collapse file tree 1 file changed +16
-11
lines changed Original file line number Diff line number Diff line change @@ -47,22 +47,27 @@ 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
+ A example thus would be the following to ensure correct resource management::
51
55
52
56
from contextlib import contextmanager
53
57
54
58
@contextmanager
55
- def tag(name):
56
- print("<%s>" % name)
57
- yield
58
- print("</%s>" % name)
59
+ def managed_resource(*args, **kwds):
60
+ # Code to acquire resource, e.g.:
61
+ resource = acquire_resource(*args, **kwds)
62
+ try:
63
+ yield resource
64
+ finally:
65
+ # Code to release resource, e.g.:
66
+ release_resource(resource)
59
67
60
- >>> with tag("h1"):
61
- ... print("foo")
62
- ...
63
- <h1>
64
- foo
65
- </h1>
68
+ >>> with managed_resource(timeout=3600) as resource:
69
+ ... # Resource is released at the end of this block,
70
+ ... # even if code in the block raises an exception
66
71
67
72
The function being decorated must return a :term: `generator `-iterator when
68
73
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