Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
C
cpython
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
Analytics
Analytics
Repository
Value Stream
Wiki
Wiki
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Commits
Issue Boards
Open sidebar
Kirill Smelkov
cpython
Commits
bde782bb
Commit
bde782bb
authored
Jul 23, 2018
by
Matthias Bussonnier
Committed by
Tal Einat
Jul 24, 2018
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
bpo-33468: Add try-finally contextlib.contextmanager example (GH-7816)
parent
a6fdddb7
Changes
1
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
17 additions
and
11 deletions
+17
-11
Doc/library/contextlib.rst
Doc/library/contextlib.rst
+17
-11
No files found.
Doc/library/contextlib.rst
View file @
bde782bb
...
...
@@ -47,22 +47,28 @@ Functions and classes provided:
function for :keyword:`with` statement context managers, without needing to
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
@contextmanager
def tag(name):
print("<%s>" % name)
yield
print("</%s>" % name)
def managed_resource(*args, **kwds):
# Code to acquire resource, e.g.:
resource = acquire_resource(*args, **kwds)
try:
yield resource
finally:
# Code to release resource, e.g.:
release_resource(resource)
>>> with tag("h1"):
... print("foo")
...
<h1>
foo
</h1>
>>> with managed_resource(timeout=3600) as resource:
... # Resource is released at the end of this block,
... # even if code in the block raises an exception
The function being decorated must return a :term:`generator`-iterator when
called. This iterator must yield exactly one value, which will be bound to
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment