Module contextlib
[hide private]
[frames] | no frames]

Module contextlib

Utilities for with-statement contexts. See PEP 343.

Classes [hide private]
GeneratorContextManager
Helper for @contextmanager decorator.
closing
Context to automatically close something at the end of a block.
Functions [hide private]
 
contextmanager(func)
@contextmanager decorator.
 
nested(*args, **kwds)
Support multiple context managers in a single with-statement.

Imports: sys


Function Details [hide private]

contextmanager(func)

 
@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>

nested(*args, **kwds)

 
Support multiple context managers in a single with-statement.

Code like this:

    with nested(A, B, C) as (X, Y, Z):
        <body>

is equivalent to this:

    with A as X:
        with B as Y:
            with C as Z:
                <body>

Decorators:
  • @contextmanager