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