Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/AnonR/anonr.TX.../opt/imh-pyth.../lib/python3....
File: contextlib.py
"""Utilities for with-statement contexts. See PEP 343."""
[0] Fix | Delete
import abc
[1] Fix | Delete
import sys
[2] Fix | Delete
import _collections_abc
[3] Fix | Delete
from collections import deque
[4] Fix | Delete
from functools import wraps
[5] Fix | Delete
from types import MethodType, GenericAlias
[6] Fix | Delete
[7] Fix | Delete
__all__ = ["asynccontextmanager", "contextmanager", "closing", "nullcontext",
[8] Fix | Delete
"AbstractContextManager", "AbstractAsyncContextManager",
[9] Fix | Delete
"AsyncExitStack", "ContextDecorator", "ExitStack",
[10] Fix | Delete
"redirect_stdout", "redirect_stderr", "suppress"]
[11] Fix | Delete
[12] Fix | Delete
[13] Fix | Delete
class AbstractContextManager(abc.ABC):
[14] Fix | Delete
[15] Fix | Delete
"""An abstract base class for context managers."""
[16] Fix | Delete
[17] Fix | Delete
__class_getitem__ = classmethod(GenericAlias)
[18] Fix | Delete
[19] Fix | Delete
def __enter__(self):
[20] Fix | Delete
"""Return `self` upon entering the runtime context."""
[21] Fix | Delete
return self
[22] Fix | Delete
[23] Fix | Delete
@abc.abstractmethod
[24] Fix | Delete
def __exit__(self, exc_type, exc_value, traceback):
[25] Fix | Delete
"""Raise any exception triggered within the runtime context."""
[26] Fix | Delete
return None
[27] Fix | Delete
[28] Fix | Delete
@classmethod
[29] Fix | Delete
def __subclasshook__(cls, C):
[30] Fix | Delete
if cls is AbstractContextManager:
[31] Fix | Delete
return _collections_abc._check_methods(C, "__enter__", "__exit__")
[32] Fix | Delete
return NotImplemented
[33] Fix | Delete
[34] Fix | Delete
[35] Fix | Delete
class AbstractAsyncContextManager(abc.ABC):
[36] Fix | Delete
[37] Fix | Delete
"""An abstract base class for asynchronous context managers."""
[38] Fix | Delete
[39] Fix | Delete
__class_getitem__ = classmethod(GenericAlias)
[40] Fix | Delete
[41] Fix | Delete
async def __aenter__(self):
[42] Fix | Delete
"""Return `self` upon entering the runtime context."""
[43] Fix | Delete
return self
[44] Fix | Delete
[45] Fix | Delete
@abc.abstractmethod
[46] Fix | Delete
async def __aexit__(self, exc_type, exc_value, traceback):
[47] Fix | Delete
"""Raise any exception triggered within the runtime context."""
[48] Fix | Delete
return None
[49] Fix | Delete
[50] Fix | Delete
@classmethod
[51] Fix | Delete
def __subclasshook__(cls, C):
[52] Fix | Delete
if cls is AbstractAsyncContextManager:
[53] Fix | Delete
return _collections_abc._check_methods(C, "__aenter__",
[54] Fix | Delete
"__aexit__")
[55] Fix | Delete
return NotImplemented
[56] Fix | Delete
[57] Fix | Delete
[58] Fix | Delete
class ContextDecorator(object):
[59] Fix | Delete
"A base class or mixin that enables context managers to work as decorators."
[60] Fix | Delete
[61] Fix | Delete
def _recreate_cm(self):
[62] Fix | Delete
"""Return a recreated instance of self.
[63] Fix | Delete
[64] Fix | Delete
Allows an otherwise one-shot context manager like
[65] Fix | Delete
_GeneratorContextManager to support use as
[66] Fix | Delete
a decorator via implicit recreation.
[67] Fix | Delete
[68] Fix | Delete
This is a private interface just for _GeneratorContextManager.
[69] Fix | Delete
See issue #11647 for details.
[70] Fix | Delete
"""
[71] Fix | Delete
return self
[72] Fix | Delete
[73] Fix | Delete
def __call__(self, func):
[74] Fix | Delete
@wraps(func)
[75] Fix | Delete
def inner(*args, **kwds):
[76] Fix | Delete
with self._recreate_cm():
[77] Fix | Delete
return func(*args, **kwds)
[78] Fix | Delete
return inner
[79] Fix | Delete
[80] Fix | Delete
[81] Fix | Delete
class _GeneratorContextManagerBase:
[82] Fix | Delete
"""Shared functionality for @contextmanager and @asynccontextmanager."""
[83] Fix | Delete
[84] Fix | Delete
def __init__(self, func, args, kwds):
[85] Fix | Delete
self.gen = func(*args, **kwds)
[86] Fix | Delete
self.func, self.args, self.kwds = func, args, kwds
[87] Fix | Delete
# Issue 19330: ensure context manager instances have good docstrings
[88] Fix | Delete
doc = getattr(func, "__doc__", None)
[89] Fix | Delete
if doc is None:
[90] Fix | Delete
doc = type(self).__doc__
[91] Fix | Delete
self.__doc__ = doc
[92] Fix | Delete
# Unfortunately, this still doesn't provide good help output when
[93] Fix | Delete
# inspecting the created context manager instances, since pydoc
[94] Fix | Delete
# currently bypasses the instance docstring and shows the docstring
[95] Fix | Delete
# for the class instead.
[96] Fix | Delete
# See http://bugs.python.org/issue19404 for more details.
[97] Fix | Delete
[98] Fix | Delete
def _recreate_cm(self):
[99] Fix | Delete
# _GCMB instances are one-shot context managers, so the
[100] Fix | Delete
# CM must be recreated each time a decorated function is
[101] Fix | Delete
# called
[102] Fix | Delete
return self.__class__(self.func, self.args, self.kwds)
[103] Fix | Delete
[104] Fix | Delete
[105] Fix | Delete
class _GeneratorContextManager(
[106] Fix | Delete
_GeneratorContextManagerBase,
[107] Fix | Delete
AbstractContextManager,
[108] Fix | Delete
ContextDecorator,
[109] Fix | Delete
):
[110] Fix | Delete
"""Helper for @contextmanager decorator."""
[111] Fix | Delete
[112] Fix | Delete
def __enter__(self):
[113] Fix | Delete
# do not keep args and kwds alive unnecessarily
[114] Fix | Delete
# they are only needed for recreation, which is not possible anymore
[115] Fix | Delete
del self.args, self.kwds, self.func
[116] Fix | Delete
try:
[117] Fix | Delete
return next(self.gen)
[118] Fix | Delete
except StopIteration:
[119] Fix | Delete
raise RuntimeError("generator didn't yield") from None
[120] Fix | Delete
[121] Fix | Delete
def __exit__(self, typ, value, traceback):
[122] Fix | Delete
if typ is None:
[123] Fix | Delete
try:
[124] Fix | Delete
next(self.gen)
[125] Fix | Delete
except StopIteration:
[126] Fix | Delete
return False
[127] Fix | Delete
else:
[128] Fix | Delete
raise RuntimeError("generator didn't stop")
[129] Fix | Delete
else:
[130] Fix | Delete
if value is None:
[131] Fix | Delete
# Need to force instantiation so we can reliably
[132] Fix | Delete
# tell if we get the same exception back
[133] Fix | Delete
value = typ()
[134] Fix | Delete
try:
[135] Fix | Delete
self.gen.throw(typ, value, traceback)
[136] Fix | Delete
except StopIteration as exc:
[137] Fix | Delete
# Suppress StopIteration *unless* it's the same exception that
[138] Fix | Delete
# was passed to throw(). This prevents a StopIteration
[139] Fix | Delete
# raised inside the "with" statement from being suppressed.
[140] Fix | Delete
return exc is not value
[141] Fix | Delete
except RuntimeError as exc:
[142] Fix | Delete
# Don't re-raise the passed in exception. (issue27122)
[143] Fix | Delete
if exc is value:
[144] Fix | Delete
return False
[145] Fix | Delete
# Avoid suppressing if a StopIteration exception
[146] Fix | Delete
# was passed to throw() and later wrapped into a RuntimeError
[147] Fix | Delete
# (see PEP 479 for sync generators; async generators also
[148] Fix | Delete
# have this behavior). But do this only if the exception wrapped
[149] Fix | Delete
# by the RuntimeError is actually Stop(Async)Iteration (see
[150] Fix | Delete
# issue29692).
[151] Fix | Delete
if (
[152] Fix | Delete
isinstance(value, StopIteration)
[153] Fix | Delete
and exc.__cause__ is value
[154] Fix | Delete
):
[155] Fix | Delete
return False
[156] Fix | Delete
raise
[157] Fix | Delete
except BaseException as exc:
[158] Fix | Delete
# only re-raise if it's *not* the exception that was
[159] Fix | Delete
# passed to throw(), because __exit__() must not raise
[160] Fix | Delete
# an exception unless __exit__() itself failed. But throw()
[161] Fix | Delete
# has to raise the exception to signal propagation, so this
[162] Fix | Delete
# fixes the impedance mismatch between the throw() protocol
[163] Fix | Delete
# and the __exit__() protocol.
[164] Fix | Delete
if exc is not value:
[165] Fix | Delete
raise
[166] Fix | Delete
return False
[167] Fix | Delete
raise RuntimeError("generator didn't stop after throw()")
[168] Fix | Delete
[169] Fix | Delete
[170] Fix | Delete
class _AsyncGeneratorContextManager(_GeneratorContextManagerBase,
[171] Fix | Delete
AbstractAsyncContextManager):
[172] Fix | Delete
"""Helper for @asynccontextmanager decorator."""
[173] Fix | Delete
[174] Fix | Delete
async def __aenter__(self):
[175] Fix | Delete
# do not keep args and kwds alive unnecessarily
[176] Fix | Delete
# they are only needed for recreation, which is not possible anymore
[177] Fix | Delete
del self.args, self.kwds, self.func
[178] Fix | Delete
try:
[179] Fix | Delete
return await self.gen.__anext__()
[180] Fix | Delete
except StopAsyncIteration:
[181] Fix | Delete
raise RuntimeError("generator didn't yield") from None
[182] Fix | Delete
[183] Fix | Delete
async def __aexit__(self, typ, value, traceback):
[184] Fix | Delete
if typ is None:
[185] Fix | Delete
try:
[186] Fix | Delete
await self.gen.__anext__()
[187] Fix | Delete
except StopAsyncIteration:
[188] Fix | Delete
return False
[189] Fix | Delete
else:
[190] Fix | Delete
raise RuntimeError("generator didn't stop")
[191] Fix | Delete
else:
[192] Fix | Delete
if value is None:
[193] Fix | Delete
# Need to force instantiation so we can reliably
[194] Fix | Delete
# tell if we get the same exception back
[195] Fix | Delete
value = typ()
[196] Fix | Delete
try:
[197] Fix | Delete
await self.gen.athrow(typ, value, traceback)
[198] Fix | Delete
except StopAsyncIteration as exc:
[199] Fix | Delete
# Suppress StopIteration *unless* it's the same exception that
[200] Fix | Delete
# was passed to throw(). This prevents a StopIteration
[201] Fix | Delete
# raised inside the "with" statement from being suppressed.
[202] Fix | Delete
return exc is not value
[203] Fix | Delete
except RuntimeError as exc:
[204] Fix | Delete
# Don't re-raise the passed in exception. (issue27122)
[205] Fix | Delete
if exc is value:
[206] Fix | Delete
return False
[207] Fix | Delete
# Avoid suppressing if a Stop(Async)Iteration exception
[208] Fix | Delete
# was passed to athrow() and later wrapped into a RuntimeError
[209] Fix | Delete
# (see PEP 479 for sync generators; async generators also
[210] Fix | Delete
# have this behavior). But do this only if the exception wrapped
[211] Fix | Delete
# by the RuntimeError is actully Stop(Async)Iteration (see
[212] Fix | Delete
# issue29692).
[213] Fix | Delete
if (
[214] Fix | Delete
isinstance(value, (StopIteration, StopAsyncIteration))
[215] Fix | Delete
and exc.__cause__ is value
[216] Fix | Delete
):
[217] Fix | Delete
return False
[218] Fix | Delete
raise
[219] Fix | Delete
except BaseException as exc:
[220] Fix | Delete
# only re-raise if it's *not* the exception that was
[221] Fix | Delete
# passed to throw(), because __exit__() must not raise
[222] Fix | Delete
# an exception unless __exit__() itself failed. But throw()
[223] Fix | Delete
# has to raise the exception to signal propagation, so this
[224] Fix | Delete
# fixes the impedance mismatch between the throw() protocol
[225] Fix | Delete
# and the __exit__() protocol.
[226] Fix | Delete
if exc is not value:
[227] Fix | Delete
raise
[228] Fix | Delete
return False
[229] Fix | Delete
raise RuntimeError("generator didn't stop after athrow()")
[230] Fix | Delete
[231] Fix | Delete
[232] Fix | Delete
def contextmanager(func):
[233] Fix | Delete
"""@contextmanager decorator.
[234] Fix | Delete
[235] Fix | Delete
Typical usage:
[236] Fix | Delete
[237] Fix | Delete
@contextmanager
[238] Fix | Delete
def some_generator(<arguments>):
[239] Fix | Delete
<setup>
[240] Fix | Delete
try:
[241] Fix | Delete
yield <value>
[242] Fix | Delete
finally:
[243] Fix | Delete
<cleanup>
[244] Fix | Delete
[245] Fix | Delete
This makes this:
[246] Fix | Delete
[247] Fix | Delete
with some_generator(<arguments>) as <variable>:
[248] Fix | Delete
<body>
[249] Fix | Delete
[250] Fix | Delete
equivalent to this:
[251] Fix | Delete
[252] Fix | Delete
<setup>
[253] Fix | Delete
try:
[254] Fix | Delete
<variable> = <value>
[255] Fix | Delete
<body>
[256] Fix | Delete
finally:
[257] Fix | Delete
<cleanup>
[258] Fix | Delete
"""
[259] Fix | Delete
@wraps(func)
[260] Fix | Delete
def helper(*args, **kwds):
[261] Fix | Delete
return _GeneratorContextManager(func, args, kwds)
[262] Fix | Delete
return helper
[263] Fix | Delete
[264] Fix | Delete
[265] Fix | Delete
def asynccontextmanager(func):
[266] Fix | Delete
"""@asynccontextmanager decorator.
[267] Fix | Delete
[268] Fix | Delete
Typical usage:
[269] Fix | Delete
[270] Fix | Delete
@asynccontextmanager
[271] Fix | Delete
async def some_async_generator(<arguments>):
[272] Fix | Delete
<setup>
[273] Fix | Delete
try:
[274] Fix | Delete
yield <value>
[275] Fix | Delete
finally:
[276] Fix | Delete
<cleanup>
[277] Fix | Delete
[278] Fix | Delete
This makes this:
[279] Fix | Delete
[280] Fix | Delete
async with some_async_generator(<arguments>) as <variable>:
[281] Fix | Delete
<body>
[282] Fix | Delete
[283] Fix | Delete
equivalent to this:
[284] Fix | Delete
[285] Fix | Delete
<setup>
[286] Fix | Delete
try:
[287] Fix | Delete
<variable> = <value>
[288] Fix | Delete
<body>
[289] Fix | Delete
finally:
[290] Fix | Delete
<cleanup>
[291] Fix | Delete
"""
[292] Fix | Delete
@wraps(func)
[293] Fix | Delete
def helper(*args, **kwds):
[294] Fix | Delete
return _AsyncGeneratorContextManager(func, args, kwds)
[295] Fix | Delete
return helper
[296] Fix | Delete
[297] Fix | Delete
[298] Fix | Delete
class closing(AbstractContextManager):
[299] Fix | Delete
"""Context to automatically close something at the end of a block.
[300] Fix | Delete
[301] Fix | Delete
Code like this:
[302] Fix | Delete
[303] Fix | Delete
with closing(<module>.open(<arguments>)) as f:
[304] Fix | Delete
<block>
[305] Fix | Delete
[306] Fix | Delete
is equivalent to this:
[307] Fix | Delete
[308] Fix | Delete
f = <module>.open(<arguments>)
[309] Fix | Delete
try:
[310] Fix | Delete
<block>
[311] Fix | Delete
finally:
[312] Fix | Delete
f.close()
[313] Fix | Delete
[314] Fix | Delete
"""
[315] Fix | Delete
def __init__(self, thing):
[316] Fix | Delete
self.thing = thing
[317] Fix | Delete
def __enter__(self):
[318] Fix | Delete
return self.thing
[319] Fix | Delete
def __exit__(self, *exc_info):
[320] Fix | Delete
self.thing.close()
[321] Fix | Delete
[322] Fix | Delete
[323] Fix | Delete
class _RedirectStream(AbstractContextManager):
[324] Fix | Delete
[325] Fix | Delete
_stream = None
[326] Fix | Delete
[327] Fix | Delete
def __init__(self, new_target):
[328] Fix | Delete
self._new_target = new_target
[329] Fix | Delete
# We use a list of old targets to make this CM re-entrant
[330] Fix | Delete
self._old_targets = []
[331] Fix | Delete
[332] Fix | Delete
def __enter__(self):
[333] Fix | Delete
self._old_targets.append(getattr(sys, self._stream))
[334] Fix | Delete
setattr(sys, self._stream, self._new_target)
[335] Fix | Delete
return self._new_target
[336] Fix | Delete
[337] Fix | Delete
def __exit__(self, exctype, excinst, exctb):
[338] Fix | Delete
setattr(sys, self._stream, self._old_targets.pop())
[339] Fix | Delete
[340] Fix | Delete
[341] Fix | Delete
class redirect_stdout(_RedirectStream):
[342] Fix | Delete
"""Context manager for temporarily redirecting stdout to another file.
[343] Fix | Delete
[344] Fix | Delete
# How to send help() to stderr
[345] Fix | Delete
with redirect_stdout(sys.stderr):
[346] Fix | Delete
help(dir)
[347] Fix | Delete
[348] Fix | Delete
# How to write help() to a file
[349] Fix | Delete
with open('help.txt', 'w') as f:
[350] Fix | Delete
with redirect_stdout(f):
[351] Fix | Delete
help(pow)
[352] Fix | Delete
"""
[353] Fix | Delete
[354] Fix | Delete
_stream = "stdout"
[355] Fix | Delete
[356] Fix | Delete
[357] Fix | Delete
class redirect_stderr(_RedirectStream):
[358] Fix | Delete
"""Context manager for temporarily redirecting stderr to another file."""
[359] Fix | Delete
[360] Fix | Delete
_stream = "stderr"
[361] Fix | Delete
[362] Fix | Delete
[363] Fix | Delete
class suppress(AbstractContextManager):
[364] Fix | Delete
"""Context manager to suppress specified exceptions
[365] Fix | Delete
[366] Fix | Delete
After the exception is suppressed, execution proceeds with the next
[367] Fix | Delete
statement following the with statement.
[368] Fix | Delete
[369] Fix | Delete
with suppress(FileNotFoundError):
[370] Fix | Delete
os.remove(somefile)
[371] Fix | Delete
# Execution still resumes here if the file was already removed
[372] Fix | Delete
"""
[373] Fix | Delete
[374] Fix | Delete
def __init__(self, *exceptions):
[375] Fix | Delete
self._exceptions = exceptions
[376] Fix | Delete
[377] Fix | Delete
def __enter__(self):
[378] Fix | Delete
pass
[379] Fix | Delete
[380] Fix | Delete
def __exit__(self, exctype, excinst, exctb):
[381] Fix | Delete
# Unlike isinstance and issubclass, CPython exception handling
[382] Fix | Delete
# currently only looks at the concrete type hierarchy (ignoring
[383] Fix | Delete
# the instance and subclass checking hooks). While Guido considers
[384] Fix | Delete
# that a bug rather than a feature, it's a fairly hard one to fix
[385] Fix | Delete
# due to various internal implementation details. suppress provides
[386] Fix | Delete
# the simpler issubclass based semantics, rather than trying to
[387] Fix | Delete
# exactly reproduce the limitations of the CPython interpreter.
[388] Fix | Delete
#
[389] Fix | Delete
# See http://bugs.python.org/issue12029 for more details
[390] Fix | Delete
return exctype is not None and issubclass(exctype, self._exceptions)
[391] Fix | Delete
[392] Fix | Delete
[393] Fix | Delete
class _BaseExitStack:
[394] Fix | Delete
"""A base class for ExitStack and AsyncExitStack."""
[395] Fix | Delete
[396] Fix | Delete
@staticmethod
[397] Fix | Delete
def _create_exit_wrapper(cm, cm_exit):
[398] Fix | Delete
return MethodType(cm_exit, cm)
[399] Fix | Delete
[400] Fix | Delete
@staticmethod
[401] Fix | Delete
def _create_cb_wrapper(callback, /, *args, **kwds):
[402] Fix | Delete
def _exit_wrapper(exc_type, exc, tb):
[403] Fix | Delete
callback(*args, **kwds)
[404] Fix | Delete
return _exit_wrapper
[405] Fix | Delete
[406] Fix | Delete
def __init__(self):
[407] Fix | Delete
self._exit_callbacks = deque()
[408] Fix | Delete
[409] Fix | Delete
def pop_all(self):
[410] Fix | Delete
"""Preserve the context stack by transferring it to a new instance."""
[411] Fix | Delete
new_stack = type(self)()
[412] Fix | Delete
new_stack._exit_callbacks = self._exit_callbacks
[413] Fix | Delete
self._exit_callbacks = deque()
[414] Fix | Delete
return new_stack
[415] Fix | Delete
[416] Fix | Delete
def push(self, exit):
[417] Fix | Delete
"""Registers a callback with the standard __exit__ method signature.
[418] Fix | Delete
[419] Fix | Delete
Can suppress exceptions the same way __exit__ method can.
[420] Fix | Delete
Also accepts any object with an __exit__ method (registering a call
[421] Fix | Delete
to the method instead of the object itself).
[422] Fix | Delete
"""
[423] Fix | Delete
# We use an unbound method rather than a bound method to follow
[424] Fix | Delete
# the standard lookup behaviour for special methods.
[425] Fix | Delete
_cb_type = type(exit)
[426] Fix | Delete
[427] Fix | Delete
try:
[428] Fix | Delete
exit_method = _cb_type.__exit__
[429] Fix | Delete
except AttributeError:
[430] Fix | Delete
# Not a context manager, so assume it's a callable.
[431] Fix | Delete
self._push_exit_callback(exit)
[432] Fix | Delete
else:
[433] Fix | Delete
self._push_cm_exit(exit, exit_method)
[434] Fix | Delete
return exit # Allow use as a decorator.
[435] Fix | Delete
[436] Fix | Delete
def enter_context(self, cm):
[437] Fix | Delete
"""Enters the supplied context manager.
[438] Fix | Delete
[439] Fix | Delete
If successful, also pushes its __exit__ method as a callback and
[440] Fix | Delete
returns the result of the __enter__ method.
[441] Fix | Delete
"""
[442] Fix | Delete
# We look up the special methods on the type to match the with
[443] Fix | Delete
# statement.
[444] Fix | Delete
_cm_type = type(cm)
[445] Fix | Delete
_exit = _cm_type.__exit__
[446] Fix | Delete
result = _cm_type.__enter__(cm)
[447] Fix | Delete
self._push_cm_exit(cm, _exit)
[448] Fix | Delete
return result
[449] Fix | Delete
[450] Fix | Delete
def callback(self, callback, /, *args, **kwds):
[451] Fix | Delete
"""Registers an arbitrary callback and arguments.
[452] Fix | Delete
[453] Fix | Delete
Cannot suppress exceptions.
[454] Fix | Delete
"""
[455] Fix | Delete
_exit_wrapper = self._create_cb_wrapper(callback, *args, **kwds)
[456] Fix | Delete
[457] Fix | Delete
# We changed the signature, so using @wraps is not appropriate, but
[458] Fix | Delete
# setting __wrapped__ may still help with introspection.
[459] Fix | Delete
_exit_wrapper.__wrapped__ = callback
[460] Fix | Delete
self._push_exit_callback(_exit_wrapper)
[461] Fix | Delete
return callback # Allow use as a decorator
[462] Fix | Delete
[463] Fix | Delete
def _push_cm_exit(self, cm, cm_exit):
[464] Fix | Delete
"""Helper to correctly register callbacks to __exit__ methods."""
[465] Fix | Delete
_exit_wrapper = self._create_exit_wrapper(cm, cm_exit)
[466] Fix | Delete
self._push_exit_callback(_exit_wrapper, True)
[467] Fix | Delete
[468] Fix | Delete
def _push_exit_callback(self, callback, is_sync=True):
[469] Fix | Delete
self._exit_callbacks.append((is_sync, callback))
[470] Fix | Delete
[471] Fix | Delete
[472] Fix | Delete
# Inspired by discussions on http://bugs.python.org/issue13585
[473] Fix | Delete
class ExitStack(_BaseExitStack, AbstractContextManager):
[474] Fix | Delete
"""Context manager for dynamic management of a stack of exit callbacks.
[475] Fix | Delete
[476] Fix | Delete
For example:
[477] Fix | Delete
with ExitStack() as stack:
[478] Fix | Delete
files = [stack.enter_context(open(fname)) for fname in filenames]
[479] Fix | Delete
# All opened files will automatically be closed at the end of
[480] Fix | Delete
# the with statement, even if attempts to open files later
[481] Fix | Delete
# in the list raise an exception.
[482] Fix | Delete
"""
[483] Fix | Delete
[484] Fix | Delete
def __enter__(self):
[485] Fix | Delete
return self
[486] Fix | Delete
[487] Fix | Delete
def __exit__(self, *exc_details):
[488] Fix | Delete
received_exc = exc_details[0] is not None
[489] Fix | Delete
[490] Fix | Delete
# We manipulate the exception state so it behaves as though
[491] Fix | Delete
# we were actually nesting multiple with statements
[492] Fix | Delete
frame_exc = sys.exc_info()[1]
[493] Fix | Delete
def _fix_exception_context(new_exc, old_exc):
[494] Fix | Delete
# Context may not be correct, so find the end of the chain
[495] Fix | Delete
while 1:
[496] Fix | Delete
exc_context = new_exc.__context__
[497] Fix | Delete
if exc_context is old_exc:
[498] Fix | Delete
# Context is already set correctly (see issue 20317)
[499] Fix | Delete
12
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function