"""Utilities for with-statement contexts. See PEP 343."""
from functools import wraps
from warnings import warn
__all__ = ["contextmanager", "nested", "closing"]
class GeneratorContextManager(object):
"""Helper for @contextmanager decorator."""
raise RuntimeError("generator didn't yield")
def __exit__(self, type, value, traceback):
raise RuntimeError("generator didn't stop")
# Need to force instantiation so we can reliably
# tell if we get the same exception back
self.gen.throw(type, value, traceback)
raise RuntimeError("generator didn't stop after throw()")
except StopIteration, exc:
# Suppress the exception *unless* it's the same exception that
# was passed to throw(). This prevents a StopIteration
# raised inside the "with" statement from being suppressed
# only re-raise if it's *not* the exception that was
# passed to throw(), because __exit__() must not raise
# an exception unless __exit__() itself failed. But throw()
# has to raise the exception to signal propagation, so this
# fixes the impedance mismatch between the throw() protocol
# and the __exit__() protocol.
if sys.exc_info()[1] is not value:
def contextmanager(func):
"""@contextmanager decorator.
def some_generator(<arguments>):
with some_generator(<arguments>) as <variable>:
def helper(*args, **kwds):
return GeneratorContextManager(func(*args, **kwds))
"""Combine multiple context managers into a single nested context manager.
This function has been deprecated in favour of the multiple manager form
The one advantage of this function over the multiple manager form of the
with statement is that argument unpacking allows it to be
used with a variable number of context managers as follows:
warn("With-statements now directly support multiple context managers",
if exc != (None, None, None):
# Don't rely on sys.exc_info() still containing
# the right information. Another exception may
# have been raised and caught by an exit method
raise exc[0], exc[1], exc[2]
"""Context to automatically close something at the end of a block.
with closing(<module>.open(<arguments>)) as f:
f = <module>.open(<arguments>)
def __init__(self, thing):
def __exit__(self, *exc_info):