PyDocs

Nav

Python Runtime Services

contextmanager

contextlib

decorator (source)
  • @contextmanager
@contextmanager decorator.

Typical usage:

    @contextmanager
    def some_generator(<arguments>):
        <setup>
        try:
            yield <value>
        finally:
            <cleanup>

This makes this:

    with some_generator(<arguments>) as <variable>:
        <body>

equivalent to this:

    <setup>
    try:
        <variable> = <value>
        <body>
    finally:
        <cleanup>
Changed in 3.2
  • 3.2: Use of ContextDecorator.
1 Example
>>> from contextlib import contextmanager
>>> @contextmanager
... def singleuse():
...     print("Before")
...     yield
...     print("After")
...
>>> cm = singleuse()
>>> with cm:
...     pass
...
Before
After
>>> with cm:
...     pass
...
Traceback (most recent call last):
    ...
RuntimeError: generator didn't yield
from the Python docs
See Also
No see-alsos for contextlib/contextmanager
0 Notes
No notes for contextmanager