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
[6] Fix | Delete
__all__ = ["contextmanager", "closing", "AbstractContextManager",
[7] Fix | Delete
"ContextDecorator", "ExitStack", "redirect_stdout",
[8] Fix | Delete
"redirect_stderr", "suppress"]
[9] Fix | Delete
[10] Fix | Delete
[11] Fix | Delete
class AbstractContextManager(abc.ABC):
[12] Fix | Delete
[13] Fix | Delete
"""An abstract base class for context managers."""
[14] Fix | Delete
[15] Fix | Delete
def __enter__(self):
[16] Fix | Delete
"""Return `self` upon entering the runtime context."""
[17] Fix | Delete
return self
[18] Fix | Delete
[19] Fix | Delete
@abc.abstractmethod
[20] Fix | Delete
def __exit__(self, exc_type, exc_value, traceback):
[21] Fix | Delete
"""Raise any exception triggered within the runtime context."""
[22] Fix | Delete
return None
[23] Fix | Delete
[24] Fix | Delete
@classmethod
[25] Fix | Delete
def __subclasshook__(cls, C):
[26] Fix | Delete
if cls is AbstractContextManager:
[27] Fix | Delete
return _collections_abc._check_methods(C, "__enter__", "__exit__")
[28] Fix | Delete
return NotImplemented
[29] Fix | Delete
[30] Fix | Delete
[31] Fix | Delete
class ContextDecorator(object):
[32] Fix | Delete
"A base class or mixin that enables context managers to work as decorators."
[33] Fix | Delete
[34] Fix | Delete
def _recreate_cm(self):
[35] Fix | Delete
"""Return a recreated instance of self.
[36] Fix | Delete
[37] Fix | Delete
Allows an otherwise one-shot context manager like
[38] Fix | Delete
_GeneratorContextManager to support use as
[39] Fix | Delete
a decorator via implicit recreation.
[40] Fix | Delete
[41] Fix | Delete
This is a private interface just for _GeneratorContextManager.
[42] Fix | Delete
See issue #11647 for details.
[43] Fix | Delete
"""
[44] Fix | Delete
return self
[45] Fix | Delete
[46] Fix | Delete
def __call__(self, func):
[47] Fix | Delete
@wraps(func)
[48] Fix | Delete
def inner(*args, **kwds):
[49] Fix | Delete
with self._recreate_cm():
[50] Fix | Delete
return func(*args, **kwds)
[51] Fix | Delete
return inner
[52] Fix | Delete
[53] Fix | Delete
[54] Fix | Delete
class _GeneratorContextManager(ContextDecorator, AbstractContextManager):
[55] Fix | Delete
"""Helper for @contextmanager decorator."""
[56] Fix | Delete
[57] Fix | Delete
def __init__(self, func, args, kwds):
[58] Fix | Delete
self.gen = func(*args, **kwds)
[59] Fix | Delete
self.func, self.args, self.kwds = func, args, kwds
[60] Fix | Delete
# Issue 19330: ensure context manager instances have good docstrings
[61] Fix | Delete
doc = getattr(func, "__doc__", None)
[62] Fix | Delete
if doc is None:
[63] Fix | Delete
doc = type(self).__doc__
[64] Fix | Delete
self.__doc__ = doc
[65] Fix | Delete
# Unfortunately, this still doesn't provide good help output when
[66] Fix | Delete
# inspecting the created context manager instances, since pydoc
[67] Fix | Delete
# currently bypasses the instance docstring and shows the docstring
[68] Fix | Delete
# for the class instead.
[69] Fix | Delete
# See http://bugs.python.org/issue19404 for more details.
[70] Fix | Delete
[71] Fix | Delete
def _recreate_cm(self):
[72] Fix | Delete
# _GCM instances are one-shot context managers, so the
[73] Fix | Delete
# CM must be recreated each time a decorated function is
[74] Fix | Delete
# called
[75] Fix | Delete
return self.__class__(self.func, self.args, self.kwds)
[76] Fix | Delete
[77] Fix | Delete
def __enter__(self):
[78] Fix | Delete
try:
[79] Fix | Delete
return next(self.gen)
[80] Fix | Delete
except StopIteration:
[81] Fix | Delete
raise RuntimeError("generator didn't yield") from None
[82] Fix | Delete
[83] Fix | Delete
def __exit__(self, type, value, traceback):
[84] Fix | Delete
if type is None:
[85] Fix | Delete
try:
[86] Fix | Delete
next(self.gen)
[87] Fix | Delete
except StopIteration:
[88] Fix | Delete
return False
[89] Fix | Delete
else:
[90] Fix | Delete
raise RuntimeError("generator didn't stop")
[91] Fix | Delete
else:
[92] Fix | Delete
if value is None:
[93] Fix | Delete
# Need to force instantiation so we can reliably
[94] Fix | Delete
# tell if we get the same exception back
[95] Fix | Delete
value = type()
[96] Fix | Delete
try:
[97] Fix | Delete
self.gen.throw(type, value, traceback)
[98] Fix | Delete
except StopIteration as exc:
[99] Fix | Delete
# Suppress StopIteration *unless* it's the same exception that
[100] Fix | Delete
# was passed to throw(). This prevents a StopIteration
[101] Fix | Delete
# raised inside the "with" statement from being suppressed.
[102] Fix | Delete
return exc is not value
[103] Fix | Delete
except RuntimeError as exc:
[104] Fix | Delete
# Don't re-raise the passed in exception. (issue27122)
[105] Fix | Delete
if exc is value:
[106] Fix | Delete
return False
[107] Fix | Delete
# Likewise, avoid suppressing if a StopIteration exception
[108] Fix | Delete
# was passed to throw() and later wrapped into a RuntimeError
[109] Fix | Delete
# (see PEP 479).
[110] Fix | Delete
if type is StopIteration and exc.__cause__ is value:
[111] Fix | Delete
return False
[112] Fix | Delete
raise
[113] Fix | Delete
except:
[114] Fix | Delete
# only re-raise if it's *not* the exception that was
[115] Fix | Delete
# passed to throw(), because __exit__() must not raise
[116] Fix | Delete
# an exception unless __exit__() itself failed. But throw()
[117] Fix | Delete
# has to raise the exception to signal propagation, so this
[118] Fix | Delete
# fixes the impedance mismatch between the throw() protocol
[119] Fix | Delete
# and the __exit__() protocol.
[120] Fix | Delete
#
[121] Fix | Delete
if sys.exc_info()[1] is value:
[122] Fix | Delete
return False
[123] Fix | Delete
raise
[124] Fix | Delete
raise RuntimeError("generator didn't stop after throw()")
[125] Fix | Delete
[126] Fix | Delete
[127] Fix | Delete
def contextmanager(func):
[128] Fix | Delete
"""@contextmanager decorator.
[129] Fix | Delete
[130] Fix | Delete
Typical usage:
[131] Fix | Delete
[132] Fix | Delete
@contextmanager
[133] Fix | Delete
def some_generator(<arguments>):
[134] Fix | Delete
<setup>
[135] Fix | Delete
try:
[136] Fix | Delete
yield <value>
[137] Fix | Delete
finally:
[138] Fix | Delete
<cleanup>
[139] Fix | Delete
[140] Fix | Delete
This makes this:
[141] Fix | Delete
[142] Fix | Delete
with some_generator(<arguments>) as <variable>:
[143] Fix | Delete
<body>
[144] Fix | Delete
[145] Fix | Delete
equivalent to this:
[146] Fix | Delete
[147] Fix | Delete
<setup>
[148] Fix | Delete
try:
[149] Fix | Delete
<variable> = <value>
[150] Fix | Delete
<body>
[151] Fix | Delete
finally:
[152] Fix | Delete
<cleanup>
[153] Fix | Delete
[154] Fix | Delete
"""
[155] Fix | Delete
@wraps(func)
[156] Fix | Delete
def helper(*args, **kwds):
[157] Fix | Delete
return _GeneratorContextManager(func, args, kwds)
[158] Fix | Delete
return helper
[159] Fix | Delete
[160] Fix | Delete
[161] Fix | Delete
class closing(AbstractContextManager):
[162] Fix | Delete
"""Context to automatically close something at the end of a block.
[163] Fix | Delete
[164] Fix | Delete
Code like this:
[165] Fix | Delete
[166] Fix | Delete
with closing(<module>.open(<arguments>)) as f:
[167] Fix | Delete
<block>
[168] Fix | Delete
[169] Fix | Delete
is equivalent to this:
[170] Fix | Delete
[171] Fix | Delete
f = <module>.open(<arguments>)
[172] Fix | Delete
try:
[173] Fix | Delete
<block>
[174] Fix | Delete
finally:
[175] Fix | Delete
f.close()
[176] Fix | Delete
[177] Fix | Delete
"""
[178] Fix | Delete
def __init__(self, thing):
[179] Fix | Delete
self.thing = thing
[180] Fix | Delete
def __enter__(self):
[181] Fix | Delete
return self.thing
[182] Fix | Delete
def __exit__(self, *exc_info):
[183] Fix | Delete
self.thing.close()
[184] Fix | Delete
[185] Fix | Delete
[186] Fix | Delete
class _RedirectStream(AbstractContextManager):
[187] Fix | Delete
[188] Fix | Delete
_stream = None
[189] Fix | Delete
[190] Fix | Delete
def __init__(self, new_target):
[191] Fix | Delete
self._new_target = new_target
[192] Fix | Delete
# We use a list of old targets to make this CM re-entrant
[193] Fix | Delete
self._old_targets = []
[194] Fix | Delete
[195] Fix | Delete
def __enter__(self):
[196] Fix | Delete
self._old_targets.append(getattr(sys, self._stream))
[197] Fix | Delete
setattr(sys, self._stream, self._new_target)
[198] Fix | Delete
return self._new_target
[199] Fix | Delete
[200] Fix | Delete
def __exit__(self, exctype, excinst, exctb):
[201] Fix | Delete
setattr(sys, self._stream, self._old_targets.pop())
[202] Fix | Delete
[203] Fix | Delete
[204] Fix | Delete
class redirect_stdout(_RedirectStream):
[205] Fix | Delete
"""Context manager for temporarily redirecting stdout to another file.
[206] Fix | Delete
[207] Fix | Delete
# How to send help() to stderr
[208] Fix | Delete
with redirect_stdout(sys.stderr):
[209] Fix | Delete
help(dir)
[210] Fix | Delete
[211] Fix | Delete
# How to write help() to a file
[212] Fix | Delete
with open('help.txt', 'w') as f:
[213] Fix | Delete
with redirect_stdout(f):
[214] Fix | Delete
help(pow)
[215] Fix | Delete
"""
[216] Fix | Delete
[217] Fix | Delete
_stream = "stdout"
[218] Fix | Delete
[219] Fix | Delete
[220] Fix | Delete
class redirect_stderr(_RedirectStream):
[221] Fix | Delete
"""Context manager for temporarily redirecting stderr to another file."""
[222] Fix | Delete
[223] Fix | Delete
_stream = "stderr"
[224] Fix | Delete
[225] Fix | Delete
[226] Fix | Delete
class suppress(AbstractContextManager):
[227] Fix | Delete
"""Context manager to suppress specified exceptions
[228] Fix | Delete
[229] Fix | Delete
After the exception is suppressed, execution proceeds with the next
[230] Fix | Delete
statement following the with statement.
[231] Fix | Delete
[232] Fix | Delete
with suppress(FileNotFoundError):
[233] Fix | Delete
os.remove(somefile)
[234] Fix | Delete
# Execution still resumes here if the file was already removed
[235] Fix | Delete
"""
[236] Fix | Delete
[237] Fix | Delete
def __init__(self, *exceptions):
[238] Fix | Delete
self._exceptions = exceptions
[239] Fix | Delete
[240] Fix | Delete
def __enter__(self):
[241] Fix | Delete
pass
[242] Fix | Delete
[243] Fix | Delete
def __exit__(self, exctype, excinst, exctb):
[244] Fix | Delete
# Unlike isinstance and issubclass, CPython exception handling
[245] Fix | Delete
# currently only looks at the concrete type hierarchy (ignoring
[246] Fix | Delete
# the instance and subclass checking hooks). While Guido considers
[247] Fix | Delete
# that a bug rather than a feature, it's a fairly hard one to fix
[248] Fix | Delete
# due to various internal implementation details. suppress provides
[249] Fix | Delete
# the simpler issubclass based semantics, rather than trying to
[250] Fix | Delete
# exactly reproduce the limitations of the CPython interpreter.
[251] Fix | Delete
#
[252] Fix | Delete
# See http://bugs.python.org/issue12029 for more details
[253] Fix | Delete
return exctype is not None and issubclass(exctype, self._exceptions)
[254] Fix | Delete
[255] Fix | Delete
[256] Fix | Delete
# Inspired by discussions on http://bugs.python.org/issue13585
[257] Fix | Delete
class ExitStack(AbstractContextManager):
[258] Fix | Delete
"""Context manager for dynamic management of a stack of exit callbacks
[259] Fix | Delete
[260] Fix | Delete
For example:
[261] Fix | Delete
[262] Fix | Delete
with ExitStack() as stack:
[263] Fix | Delete
files = [stack.enter_context(open(fname)) for fname in filenames]
[264] Fix | Delete
# All opened files will automatically be closed at the end of
[265] Fix | Delete
# the with statement, even if attempts to open files later
[266] Fix | Delete
# in the list raise an exception
[267] Fix | Delete
[268] Fix | Delete
"""
[269] Fix | Delete
def __init__(self):
[270] Fix | Delete
self._exit_callbacks = deque()
[271] Fix | Delete
[272] Fix | Delete
def pop_all(self):
[273] Fix | Delete
"""Preserve the context stack by transferring it to a new instance"""
[274] Fix | Delete
new_stack = type(self)()
[275] Fix | Delete
new_stack._exit_callbacks = self._exit_callbacks
[276] Fix | Delete
self._exit_callbacks = deque()
[277] Fix | Delete
return new_stack
[278] Fix | Delete
[279] Fix | Delete
def _push_cm_exit(self, cm, cm_exit):
[280] Fix | Delete
"""Helper to correctly register callbacks to __exit__ methods"""
[281] Fix | Delete
def _exit_wrapper(*exc_details):
[282] Fix | Delete
return cm_exit(cm, *exc_details)
[283] Fix | Delete
_exit_wrapper.__self__ = cm
[284] Fix | Delete
self.push(_exit_wrapper)
[285] Fix | Delete
[286] Fix | Delete
def push(self, exit):
[287] Fix | Delete
"""Registers a callback with the standard __exit__ method signature
[288] Fix | Delete
[289] Fix | Delete
Can suppress exceptions the same way __exit__ methods can.
[290] Fix | Delete
[291] Fix | Delete
Also accepts any object with an __exit__ method (registering a call
[292] Fix | Delete
to the method instead of the object itself)
[293] Fix | Delete
"""
[294] Fix | Delete
# We use an unbound method rather than a bound method to follow
[295] Fix | Delete
# the standard lookup behaviour for special methods
[296] Fix | Delete
_cb_type = type(exit)
[297] Fix | Delete
try:
[298] Fix | Delete
exit_method = _cb_type.__exit__
[299] Fix | Delete
except AttributeError:
[300] Fix | Delete
# Not a context manager, so assume its a callable
[301] Fix | Delete
self._exit_callbacks.append(exit)
[302] Fix | Delete
else:
[303] Fix | Delete
self._push_cm_exit(exit, exit_method)
[304] Fix | Delete
return exit # Allow use as a decorator
[305] Fix | Delete
[306] Fix | Delete
def callback(self, callback, *args, **kwds):
[307] Fix | Delete
"""Registers an arbitrary callback and arguments.
[308] Fix | Delete
[309] Fix | Delete
Cannot suppress exceptions.
[310] Fix | Delete
"""
[311] Fix | Delete
def _exit_wrapper(exc_type, exc, tb):
[312] Fix | Delete
callback(*args, **kwds)
[313] Fix | Delete
# We changed the signature, so using @wraps is not appropriate, but
[314] Fix | Delete
# setting __wrapped__ may still help with introspection
[315] Fix | Delete
_exit_wrapper.__wrapped__ = callback
[316] Fix | Delete
self.push(_exit_wrapper)
[317] Fix | Delete
return callback # Allow use as a decorator
[318] Fix | Delete
[319] Fix | Delete
def enter_context(self, cm):
[320] Fix | Delete
"""Enters the supplied context manager
[321] Fix | Delete
[322] Fix | Delete
If successful, also pushes its __exit__ method as a callback and
[323] Fix | Delete
returns the result of the __enter__ method.
[324] Fix | Delete
"""
[325] Fix | Delete
# We look up the special methods on the type to match the with statement
[326] Fix | Delete
_cm_type = type(cm)
[327] Fix | Delete
_exit = _cm_type.__exit__
[328] Fix | Delete
result = _cm_type.__enter__(cm)
[329] Fix | Delete
self._push_cm_exit(cm, _exit)
[330] Fix | Delete
return result
[331] Fix | Delete
[332] Fix | Delete
def close(self):
[333] Fix | Delete
"""Immediately unwind the context stack"""
[334] Fix | Delete
self.__exit__(None, None, None)
[335] Fix | Delete
[336] Fix | Delete
def __exit__(self, *exc_details):
[337] Fix | Delete
received_exc = exc_details[0] is not None
[338] Fix | Delete
[339] Fix | Delete
# We manipulate the exception state so it behaves as though
[340] Fix | Delete
# we were actually nesting multiple with statements
[341] Fix | Delete
frame_exc = sys.exc_info()[1]
[342] Fix | Delete
def _fix_exception_context(new_exc, old_exc):
[343] Fix | Delete
# Context may not be correct, so find the end of the chain
[344] Fix | Delete
while 1:
[345] Fix | Delete
exc_context = new_exc.__context__
[346] Fix | Delete
if exc_context is old_exc:
[347] Fix | Delete
# Context is already set correctly (see issue 20317)
[348] Fix | Delete
return
[349] Fix | Delete
if exc_context is None or exc_context is frame_exc:
[350] Fix | Delete
break
[351] Fix | Delete
new_exc = exc_context
[352] Fix | Delete
# Change the end of the chain to point to the exception
[353] Fix | Delete
# we expect it to reference
[354] Fix | Delete
new_exc.__context__ = old_exc
[355] Fix | Delete
[356] Fix | Delete
# Callbacks are invoked in LIFO order to match the behaviour of
[357] Fix | Delete
# nested context managers
[358] Fix | Delete
suppressed_exc = False
[359] Fix | Delete
pending_raise = False
[360] Fix | Delete
while self._exit_callbacks:
[361] Fix | Delete
cb = self._exit_callbacks.pop()
[362] Fix | Delete
try:
[363] Fix | Delete
if cb(*exc_details):
[364] Fix | Delete
suppressed_exc = True
[365] Fix | Delete
pending_raise = False
[366] Fix | Delete
exc_details = (None, None, None)
[367] Fix | Delete
except:
[368] Fix | Delete
new_exc_details = sys.exc_info()
[369] Fix | Delete
# simulate the stack of exceptions by setting the context
[370] Fix | Delete
_fix_exception_context(new_exc_details[1], exc_details[1])
[371] Fix | Delete
pending_raise = True
[372] Fix | Delete
exc_details = new_exc_details
[373] Fix | Delete
if pending_raise:
[374] Fix | Delete
try:
[375] Fix | Delete
# bare "raise exc_details[1]" replaces our carefully
[376] Fix | Delete
# set-up context
[377] Fix | Delete
fixed_ctx = exc_details[1].__context__
[378] Fix | Delete
raise exc_details[1]
[379] Fix | Delete
except BaseException:
[380] Fix | Delete
exc_details[1].__context__ = fixed_ctx
[381] Fix | Delete
raise
[382] Fix | Delete
return received_exc and suppressed_exc
[383] Fix | Delete
[384] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function