File tree Expand file tree Collapse file tree 1 file changed +17
-11
lines changed Expand file tree Collapse file tree 1 file changed +17
-11
lines changed Original file line number Diff line number Diff line change @@ -36,22 +36,28 @@ Functions and classes provided:
36
36
function for :keyword: `with ` statement context managers, without needing to
37
37
create a class or separate :meth: `__enter__ ` and :meth: `__exit__ ` methods.
38
38
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::
40
45
41
46
from contextlib import contextmanager
42
47
43
48
@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)
48
57
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
55
61
56
62
The function being decorated must return a :term: `generator `-iterator when
57
63
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