mirror of
https://github.com/python/cpython.git
synced 2025-11-09 14:06:30 +00:00
bpo-33468: Add try-finally contextlib.contextmanager example (GH-7816)
This commit is contained in:
parent
a6fdddb7df
commit
bde782bb59
1 changed files with 17 additions and 11 deletions
|
|
@ -47,22 +47,28 @@ Functions and classes provided:
|
||||||
function for :keyword:`with` statement context managers, without needing to
|
function for :keyword:`with` statement context managers, without needing to
|
||||||
create a class or separate :meth:`__enter__` and :meth:`__exit__` methods.
|
create a class or separate :meth:`__enter__` and :meth:`__exit__` methods.
|
||||||
|
|
||||||
A simple example (this is not recommended as a real way of generating HTML!)::
|
While many objects natively support use in with statements, sometimes a
|
||||||
|
resource needs to be managed that isn't a context manager in its own right,
|
||||||
|
and doesn't implement a ``close()`` method for use with ``contextlib.closing``
|
||||||
|
|
||||||
|
An abstract example would be the following to ensure correct resource
|
||||||
|
management::
|
||||||
|
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def tag(name):
|
def managed_resource(*args, **kwds):
|
||||||
print("<%s>" % name)
|
# Code to acquire resource, e.g.:
|
||||||
yield
|
resource = acquire_resource(*args, **kwds)
|
||||||
print("</%s>" % name)
|
try:
|
||||||
|
yield resource
|
||||||
|
finally:
|
||||||
|
# Code to release resource, e.g.:
|
||||||
|
release_resource(resource)
|
||||||
|
|
||||||
>>> with tag("h1"):
|
>>> with managed_resource(timeout=3600) as resource:
|
||||||
... print("foo")
|
... # Resource is released at the end of this block,
|
||||||
...
|
... # even if code in the block raises an exception
|
||||||
<h1>
|
|
||||||
foo
|
|
||||||
</h1>
|
|
||||||
|
|
||||||
The function being decorated must return a :term:`generator`-iterator when
|
The function being decorated must return a :term:`generator`-iterator when
|
||||||
called. This iterator must yield exactly one value, which will be bound to
|
called. This iterator must yield exactly one value, which will be bound to
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue