@@ -24,22 +24,28 @@ Functions provided: |
|
|
24 |
24 |
function for :keyword:`with` statement context managers, without needing to |
25 |
25 |
create a class or separate :meth:`__enter__` and :meth:`__exit__` methods. |
26 |
26 |
|
27 |
|
- A simple example (this is not recommended as a real way of generating HTML!):: |
|
27 |
+ While many objects natively support use in with statements, sometimes a |
|
28 |
+ resource needs to be managed that isn't a context manager in its own right, |
|
29 |
+ and doesn't implement a ``close()`` method for use with ``contextlib.closing`` |
|
30 |
+ |
|
31 |
+ An abstract example would be the following to ensure correct resource |
|
32 |
+ management:: |
28 |
33 |
|
29 |
34 |
from contextlib import contextmanager |
30 |
35 |
|
31 |
36 |
@contextmanager |
32 |
|
- def tag(name): |
33 |
|
- print "<%s>" % name |
34 |
|
- yield |
35 |
|
- print "</%s>" % name |
36 |
|
- |
37 |
|
- >>> with tag("h1"): |
38 |
|
- ... print "foo" |
39 |
|
- ... |
40 |
|
- |
41 |
|
- foo |
42 |
|
- |
|
37 |
+ def managed_resource(*args, **kwds): |
|
38 |
+ # Code to acquire resource, e.g.: |
|
39 |
+ resource = acquire_resource(*args, **kwds) |
|
40 |
+ try: |
|
41 |
+ yield resource |
|
42 |
+ finally: |
|
43 |
+ # Code to release resource, e.g.: |
|
44 |
+ release_resource(resource) |
|
45 |
+ |
|
46 |
+ >>> with managed_resource(timeout=3600) as resource: |
|
47 |
+ ... # Resource is released at the end of this block, |
|
48 |
+ ... # even if code in the block raises an exception |
43 |
49 |
|
44 |
50 |
The function being decorated must return a :term:`generator`-iterator when |
45 |
51 |
called. This iterator must yield exactly one value, which will be bound to |