/
usr
/
lib64
/
python3.9
/
/usr/lib64/python3.9
mkdir
upload
Name
Size
Mode
Actions
asyncio/
-
0755
rm
collections/
-
0755
rm
concurrent/
-
0755
rm
config-3.9-x86_64-linux-gnu/
-
0755
rm
ctypes/
-
0755
rm
curses/
-
0755
rm
dbm/
-
0755
rm
distutils/
-
0755
rm
email/
-
0755
rm
encodings/
-
0755
rm
ensurepip/
-
0755
rm
html/
-
0755
rm
http/
-
0755
rm
importlib/
-
0755
rm
json/
-
0755
rm
lib-dynload/
-
0755
rm
lib2to3/
-
0755
rm
logging/
-
0755
rm
multiprocessing/
-
0755
rm
pydoc_data/
-
0755
rm
site-packages/
-
0755
rm
sqlite3/
-
0755
rm
unittest/
-
0755
rm
urllib/
-
0755
rm
venv/
-
0755
rm
wsgiref/
-
0755
rm
xml/
-
0755
rm
xmlrpc/
-
0755
rm
zoneinfo/
-
0755
rm
__pycache__/
-
0755
rm
abc.py
4920
0644
edit
dl
rm
aifc.py
32605
0644
edit
dl
rm
antigravity.py
500
0644
edit
dl
rm
argparse.py
98119
0644
edit
dl
rm
ast.py
56256
0644
edit
dl
rm
asynchat.py
11321
0644
edit
dl
rm
asyncore.py
20102
0644
edit
dl
rm
base64.py
19859
0755
edit
dl
rm
bdb.py
31389
0644
edit
dl
rm
binhex.py
14784
0644
edit
dl
rm
bisect.py
2350
0644
edit
dl
rm
bz2.py
12447
0644
edit
dl
rm
calendar.py
24832
0644
edit
dl
rm
cgi.py
33932
0755
edit
dl
rm
cgitb.py
12096
0644
edit
dl
rm
chunk.py
5435
0644
edit
dl
rm
cmd.py
14860
0644
edit
dl
rm
code.py
10622
0644
edit
dl
rm
codecs.py
36673
0644
edit
dl
rm
codeop.py
6326
0644
edit
dl
rm
colorsys.py
4064
0644
edit
dl
rm
compileall.py
20105
0644
edit
dl
rm
configparser.py
54584
0644
edit
dl
rm
contextlib.py
24624
0644
edit
dl
rm
contextvars.py
129
0644
edit
dl
rm
copy.py
8650
0644
edit
dl
rm
copyreg.py
7274
0644
edit
dl
rm
cProfile.py
6345
0755
edit
dl
rm
crypt.py
3819
0644
edit
dl
rm
csv.py
16144
0644
edit
dl
rm
dataclasses.py
49586
0644
edit
dl
rm
datetime.py
89177
0644
edit
dl
rm
decimal.py
320
0644
edit
dl
rm
difflib.py
83307
0644
edit
dl
rm
dis.py
20570
0644
edit
dl
rm
doctest.py
104568
0644
edit
dl
rm
enum.py
39440
0644
edit
dl
rm
filecmp.py
10024
0644
edit
dl
rm
fileinput.py
14791
0644
edit
dl
rm
fnmatch.py
6004
0644
edit
dl
rm
formatter.py
15143
0644
edit
dl
rm
fractions.py
24323
0644
edit
dl
rm
ftplib.py
35496
0644
edit
dl
rm
functools.py
38881
0644
edit
dl
rm
genericpath.py
5246
0644
edit
dl
rm
getopt.py
7489
0644
edit
dl
rm
getpass.py
5990
0644
edit
dl
rm
gettext.py
27266
0644
edit
dl
rm
glob.py
5823
0644
edit
dl
rm
graphlib.py
9573
0644
edit
dl
rm
gzip.py
21772
0644
edit
dl
rm
hashlib.py
8069
0644
edit
dl
rm
heapq.py
22877
0644
edit
dl
rm
hmac.py
8043
0644
edit
dl
rm
imaplib.py
55256
0644
edit
dl
rm
imghdr.py
3808
0644
edit
dl
rm
imp.py
10536
0644
edit
dl
rm
inspect.py
118235
0644
edit
dl
rm
io.py
3541
0644
edit
dl
rm
ipaddress.py
80924
0644
edit
dl
rm
keyword.py
1047
0644
edit
dl
rm
LICENSE.txt
13937
0644
edit
dl
rm
linecache.py
5461
0644
edit
dl
rm
locale.py
78271
0644
edit
dl
rm
lzma.py
13231
0644
edit
dl
rm
mailbox.py
78794
0644
edit
dl
rm
mailcap.py
9116
0644
edit
dl
rm
mimetypes.py
21564
0644
edit
dl
rm
modulefinder.py
24401
0644
edit
dl
rm
netrc.py
5566
0644
edit
dl
rm
nntplib.py
41023
0644
edit
dl
rm
ntpath.py
26460
0644
edit
dl
rm
nturl2path.py
2887
0644
edit
dl
rm
numbers.py
10338
0644
edit
dl
rm
opcode.py
5660
0644
edit
dl
rm
operator.py
10751
0644
edit
dl
rm
optparse.py
60369
0644
edit
dl
rm
os.py
39065
0644
edit
dl
rm
pathlib.py
51134
0644
edit
dl
rm
pdb.py
63237
0755
edit
dl
rm
pickle.py
64920
0644
edit
dl
rm
pickletools.py
93486
0644
edit
dl
rm
pipes.py
8916
0644
edit
dl
rm
pkgutil.py
24276
0644
edit
dl
rm
platform.py
40601
0755
edit
dl
rm
plistlib.py
28248
0644
edit
dl
rm
poplib.py
15198
0644
edit
dl
rm
posixpath.py
16146
0644
edit
dl
rm
pprint.py
22527
0644
edit
dl
rm
profile.py
22881
0755
edit
dl
rm
pstats.py
29326
0644
edit
dl
rm
pty.py
4807
0644
edit
dl
rm
pyclbr.py
15255
0644
edit
dl
rm
pydoc.py
109599
0755
edit
dl
rm
py_compile.py
8203
0644
edit
dl
rm
queue.py
11496
0644
edit
dl
rm
quopri.py
7266
0755
edit
dl
rm
random.py
31484
0644
edit
dl
rm
re.py
15861
0644
edit
dl
rm
reprlib.py
5267
0644
edit
dl
rm
rlcompleter.py
7648
0644
edit
dl
rm
runpy.py
13084
0644
edit
dl
rm
sched.py
6442
0644
edit
dl
rm
secrets.py
2036
0644
edit
dl
rm
selectors.py
19536
0644
edit
dl
rm
shelve.py
8527
0644
edit
dl
rm
shlex.py
13501
0644
edit
dl
rm
shutil.py
53030
0644
edit
dl
rm
signal.py
2438
0644
edit
dl
rm
site.py
22085
0644
edit
dl
rm
smtpd.py
34821
0755
edit
dl
rm
smtplib.py
45405
0755
edit
dl
rm
sndhdr.py
7099
0644
edit
dl
rm
socket.py
36915
0644
edit
dl
rm
socketserver.py
27296
0644
edit
dl
rm
sre_compile.py
27973
0644
edit
dl
rm
sre_constants.py
7177
0644
edit
dl
rm
sre_parse.py
40779
0644
edit
dl
rm
ssl.py
52622
0644
edit
dl
rm
stat.py
5485
0644
edit
dl
rm
statistics.py
38067
0644
edit
dl
rm
string.py
10566
0644
edit
dl
rm
stringprep.py
12917
0644
edit
dl
rm
struct.py
257
0644
edit
dl
rm
subprocess.py
83564
0644
edit
dl
rm
sunau.py
18158
0644
edit
dl
rm
symbol.py
2281
0644
edit
dl
rm
symtable.py
7905
0644
edit
dl
rm
sysconfig.py
25557
0644
edit
dl
rm
tabnanny.py
11406
0755
edit
dl
rm
tarfile.py
112939
0755
edit
dl
rm
telnetlib.py
23254
0644
edit
dl
rm
tempfile.py
27963
0644
edit
dl
rm
textwrap.py
19407
0644
edit
dl
rm
this.py
1003
0644
edit
dl
rm
threading.py
54176
0644
edit
dl
rm
timeit.py
13480
0755
edit
dl
rm
token.py
2368
0644
edit
dl
rm
tokenize.py
25883
0644
edit
dl
rm
trace.py
29207
0755
edit
dl
rm
traceback.py
24660
0644
edit
dl
rm
tracemalloc.py
18047
0644
edit
dl
rm
tty.py
879
0644
edit
dl
rm
types.py
9785
0644
edit
dl
rm
typing.py
77044
0644
edit
dl
rm
uu.py
7277
0644
edit
dl
rm
uuid.py
27324
0644
edit
dl
rm
warnings.py
19688
0644
edit
dl
rm
wave.py
18004
0644
edit
dl
rm
weakref.py
21560
0644
edit
dl
rm
webbrowser.py
24083
0755
edit
dl
rm
xdrlib.py
5913
0644
edit
dl
rm
zipapp.py
7535
0644
edit
dl
rm
zipfile.py
88899
0644
edit
dl
rm
zipimport.py
30765
0644
edit
dl
rm
_aix_support.py
3389
0644
edit
dl
rm
_bootlocale.py
1801
0644
edit
dl
rm
_bootsubprocess.py
2675
0644
edit
dl
rm
_collections_abc.py
29374
0644
edit
dl
rm
_compat_pickle.py
8749
0644
edit
dl
rm
_compression.py
5340
0644
edit
dl
rm
_markupbase.py
14623
0644
edit
dl
rm
_osx_support.py
21773
0644
edit
dl
rm
_pydecimal.py
228666
0644
edit
dl
rm
_pyio.py
93316
0644
edit
dl
rm
_py_abc.py
6189
0644
edit
dl
rm
_sitebuiltins.py
3115
0644
edit
dl
rm
_strptime.py
25277
0644
edit
dl
rm
_sysconfigdata__linux_x86_64-linux-gnu.py
41236
0644
edit
dl
rm
_threading_local.py
7220
0644
edit
dl
rm
_weakrefset.py
5923
0644
edit
dl
rm
__future__.py
5147
0644
edit
dl
rm
__phello__.foo.py
64
0644
edit
dl
rm
Edit:
/usr/lib64/python3.9/contextlib.py
(24624B)
"""Utilities for with-statement contexts. See PEP 343.""" import abc import sys import _collections_abc from collections import deque from functools import wraps from types import MethodType, GenericAlias __all__ = ["asynccontextmanager", "contextmanager", "closing", "nullcontext", "AbstractContextManager", "AbstractAsyncContextManager", "AsyncExitStack", "ContextDecorator", "ExitStack", "redirect_stdout", "redirect_stderr", "suppress"] class AbstractContextManager(abc.ABC): """An abstract base class for context managers.""" __class_getitem__ = classmethod(GenericAlias) def __enter__(self): """Return `self` upon entering the runtime context.""" return self @abc.abstractmethod def __exit__(self, exc_type, exc_value, traceback): """Raise any exception triggered within the runtime context.""" return None @classmethod def __subclasshook__(cls, C): if cls is AbstractContextManager: return _collections_abc._check_methods(C, "__enter__", "__exit__") return NotImplemented class AbstractAsyncContextManager(abc.ABC): """An abstract base class for asynchronous context managers.""" __class_getitem__ = classmethod(GenericAlias) async def __aenter__(self): """Return `self` upon entering the runtime context.""" return self @abc.abstractmethod async def __aexit__(self, exc_type, exc_value, traceback): """Raise any exception triggered within the runtime context.""" return None @classmethod def __subclasshook__(cls, C): if cls is AbstractAsyncContextManager: return _collections_abc._check_methods(C, "__aenter__", "__aexit__") return NotImplemented class ContextDecorator(object): "A base class or mixin that enables context managers to work as decorators." def _recreate_cm(self): """Return a recreated instance of self. Allows an otherwise one-shot context manager like _GeneratorContextManager to support use as a decorator via implicit recreation. This is a private interface just for _GeneratorContextManager. See issue #11647 for details. """ return self def __call__(self, func): @wraps(func) def inner(*args, **kwds): with self._recreate_cm(): return func(*args, **kwds) return inner class _GeneratorContextManagerBase: """Shared functionality for @contextmanager and @asynccontextmanager.""" def __init__(self, func, args, kwds): self.gen = func(*args, **kwds) self.func, self.args, self.kwds = func, args, kwds # Issue 19330: ensure context manager instances have good docstrings doc = getattr(func, "__doc__", None) if doc is None: doc = type(self).__doc__ self.__doc__ = doc # Unfortunately, this still doesn't provide good help output when # inspecting the created context manager instances, since pydoc # currently bypasses the instance docstring and shows the docstring # for the class instead. # See http://bugs.python.org/issue19404 for more details. def _recreate_cm(self): # _GCMB instances are one-shot context managers, so the # CM must be recreated each time a decorated function is # called return self.__class__(self.func, self.args, self.kwds) class _GeneratorContextManager( _GeneratorContextManagerBase, AbstractContextManager, ContextDecorator, ): """Helper for @contextmanager decorator.""" def __enter__(self): # do not keep args and kwds alive unnecessarily # they are only needed for recreation, which is not possible anymore del self.args, self.kwds, self.func try: return next(self.gen) except StopIteration: raise RuntimeError("generator didn't yield") from None def __exit__(self, typ, value, traceback): if typ is None: try: next(self.gen) except StopIteration: return False else: raise RuntimeError("generator didn't stop") else: if value is None: # Need to force instantiation so we can reliably # tell if we get the same exception back value = typ() try: self.gen.throw(typ, value, traceback) except StopIteration as exc: # Suppress StopIteration *unless* it's the same exception that # was passed to throw(). This prevents a StopIteration # raised inside the "with" statement from being suppressed. return exc is not value except RuntimeError as exc: # Don't re-raise the passed in exception. (issue27122) if exc is value: return False # Avoid suppressing if a StopIteration exception # was passed to throw() and later wrapped into a RuntimeError # (see PEP 479 for sync generators; async generators also # have this behavior). But do this only if the exception wrapped # by the RuntimeError is actually Stop(Async)Iteration (see # issue29692). if ( isinstance(value, StopIteration) and exc.__cause__ is value ): return False raise except BaseException as exc: # 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 exc is not value: raise return False raise RuntimeError("generator didn't stop after throw()") class _AsyncGeneratorContextManager(_GeneratorContextManagerBase, AbstractAsyncContextManager): """Helper for @asynccontextmanager decorator.""" async def __aenter__(self): # do not keep args and kwds alive unnecessarily # they are only needed for recreation, which is not possible anymore del self.args, self.kwds, self.func try: return await self.gen.__anext__() except StopAsyncIteration: raise RuntimeError("generator didn't yield") from None async def __aexit__(self, typ, value, traceback): if typ is None: try: await self.gen.__anext__() except StopAsyncIteration: return False else: raise RuntimeError("generator didn't stop") else: if value is None: # Need to force instantiation so we can reliably # tell if we get the same exception back value = typ() try: await self.gen.athrow(typ, value, traceback) except StopAsyncIteration as exc: # Suppress StopIteration *unless* it's the same exception that # was passed to throw(). This prevents a StopIteration # raised inside the "with" statement from being suppressed. return exc is not value except RuntimeError as exc: # Don't re-raise the passed in exception. (issue27122) if exc is value: return False # Avoid suppressing if a Stop(Async)Iteration exception # was passed to athrow() and later wrapped into a RuntimeError # (see PEP 479 for sync generators; async generators also # have this behavior). But do this only if the exception wrapped # by the RuntimeError is actully Stop(Async)Iteration (see # issue29692). if ( isinstance(value, (StopIteration, StopAsyncIteration)) and exc.__cause__ is value ): return False raise except BaseException as exc: # 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 exc is not value: raise return False raise RuntimeError("generator didn't stop after athrow()") def 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> """ @wraps(func) def helper(*args, **kwds): return _GeneratorContextManager(func, args, kwds) return helper def asynccontextmanager(func): """@asynccontextmanager decorator. Typical usage: @asynccontextmanager async def some_async_generator(<arguments>): <setup> try: yield <value> finally: <cleanup> This makes this: async with some_async_generator(<arguments>) as <variable>: <body> equivalent to this: <setup> try: <variable> = <value> <body> finally: <cleanup> """ @wraps(func) def helper(*args, **kwds): return _AsyncGeneratorContextManager(func, args, kwds) return helper class closing(AbstractContextManager): """Context to automatically close something at the end of a block. Code like this: with closing(<module>.open(<arguments>)) as f: <block> is equivalent to this: f = <module>.open(<arguments>) try: <block> finally: f.close() """ def __init__(self, thing): self.thing = thing def __enter__(self): return self.thing def __exit__(self, *exc_info): self.thing.close() class _RedirectStream(AbstractContextManager): _stream = None def __init__(self, new_target): self._new_target = new_target # We use a list of old targets to make this CM re-entrant self._old_targets = [] def __enter__(self): self._old_targets.append(getattr(sys, self._stream)) setattr(sys, self._stream, self._new_target) return self._new_target def __exit__(self, exctype, excinst, exctb): setattr(sys, self._stream, self._old_targets.pop()) class redirect_stdout(_RedirectStream): """Context manager for temporarily redirecting stdout to another file. # How to send help() to stderr with redirect_stdout(sys.stderr): help(dir) # How to write help() to a file with open('help.txt', 'w') as f: with redirect_stdout(f): help(pow) """ _stream = "stdout" class redirect_stderr(_RedirectStream): """Context manager for temporarily redirecting stderr to another file.""" _stream = "stderr" class suppress(AbstractContextManager): """Context manager to suppress specified exceptions After the exception is suppressed, execution proceeds with the next statement following the with statement. with suppress(FileNotFoundError): os.remove(somefile) # Execution still resumes here if the file was already removed """ def __init__(self, *exceptions): self._exceptions = exceptions def __enter__(self): pass def __exit__(self, exctype, excinst, exctb): # Unlike isinstance and issubclass, CPython exception handling # currently only looks at the concrete type hierarchy (ignoring # the instance and subclass checking hooks). While Guido considers # that a bug rather than a feature, it's a fairly hard one to fix # due to various internal implementation details. suppress provides # the simpler issubclass based semantics, rather than trying to # exactly reproduce the limitations of the CPython interpreter. # # See http://bugs.python.org/issue12029 for more details return exctype is not None and issubclass(exctype, self._exceptions) class _BaseExitStack: """A base class for ExitStack and AsyncExitStack.""" @staticmethod def _create_exit_wrapper(cm, cm_exit): return MethodType(cm_exit, cm) @staticmethod def _create_cb_wrapper(callback, /, *args, **kwds): def _exit_wrapper(exc_type, exc, tb): callback(*args, **kwds) return _exit_wrapper def __init__(self): self._exit_callbacks = deque() def pop_all(self): """Preserve the context stack by transferring it to a new instance.""" new_stack = type(self)() new_stack._exit_callbacks = self._exit_callbacks self._exit_callbacks = deque() return new_stack def push(self, exit): """Registers a callback with the standard __exit__ method signature. Can suppress exceptions the same way __exit__ method can. Also accepts any object with an __exit__ method (registering a call to the method instead of the object itself). """ # We use an unbound method rather than a bound method to follow # the standard lookup behaviour for special methods. _cb_type = type(exit) try: exit_method = _cb_type.__exit__ except AttributeError: # Not a context manager, so assume it's a callable. self._push_exit_callback(exit) else: self._push_cm_exit(exit, exit_method) return exit # Allow use as a decorator. def enter_context(self, cm): """Enters the supplied context manager. If successful, also pushes its __exit__ method as a callback and returns the result of the __enter__ method. """ # We look up the special methods on the type to match the with # statement. _cm_type = type(cm) _exit = _cm_type.__exit__ result = _cm_type.__enter__(cm) self._push_cm_exit(cm, _exit) return result def callback(self, callback, /, *args, **kwds): """Registers an arbitrary callback and arguments. Cannot suppress exceptions. """ _exit_wrapper = self._create_cb_wrapper(callback, *args, **kwds) # We changed the signature, so using @wraps is not appropriate, but # setting __wrapped__ may still help with introspection. _exit_wrapper.__wrapped__ = callback self._push_exit_callback(_exit_wrapper) return callback # Allow use as a decorator def _push_cm_exit(self, cm, cm_exit): """Helper to correctly register callbacks to __exit__ methods.""" _exit_wrapper = self._create_exit_wrapper(cm, cm_exit) self._push_exit_callback(_exit_wrapper, True) def _push_exit_callback(self, callback, is_sync=True): self._exit_callbacks.append((is_sync, callback)) # Inspired by discussions on http://bugs.python.org/issue13585 class ExitStack(_BaseExitStack, AbstractContextManager): """Context manager for dynamic management of a stack of exit callbacks. For example: with ExitStack() as stack: files = [stack.enter_context(open(fname)) for fname in filenames] # All opened files will automatically be closed at the end of # the with statement, even if attempts to open files later # in the list raise an exception. """ def __enter__(self): return self def __exit__(self, *exc_details): received_exc = exc_details[0] is not None # We manipulate the exception state so it behaves as though # we were actually nesting multiple with statements frame_exc = sys.exc_info()[1] def _fix_exception_context(new_exc, old_exc): # Context may not be correct, so find the end of the chain while 1: exc_context = new_exc.__context__ if exc_context is None or exc_context is old_exc: # Context is already set correctly (see issue 20317) return if exc_context is frame_exc: break new_exc = exc_context # Change the end of the chain to point to the exception # we expect it to reference new_exc.__context__ = old_exc # Callbacks are invoked in LIFO order to match the behaviour of # nested context managers suppressed_exc = False pending_raise = False while self._exit_callbacks: is_sync, cb = self._exit_callbacks.pop() assert is_sync try: if cb(*exc_details): suppressed_exc = True pending_raise = False exc_details = (None, None, None) except: new_exc_details = sys.exc_info() # simulate the stack of exceptions by setting the context _fix_exception_context(new_exc_details[1], exc_details[1]) pending_raise = True exc_details = new_exc_details if pending_raise: try: # bare "raise exc_details[1]" replaces our carefully # set-up context fixed_ctx = exc_details[1].__context__ raise exc_details[1] except BaseException: exc_details[1].__context__ = fixed_ctx raise return received_exc and suppressed_exc def close(self): """Immediately unwind the context stack.""" self.__exit__(None, None, None) # Inspired by discussions on https://bugs.python.org/issue29302 class AsyncExitStack(_BaseExitStack, AbstractAsyncContextManager): """Async context manager for dynamic management of a stack of exit callbacks. For example: async with AsyncExitStack() as stack: connections = [await stack.enter_async_context(get_connection()) for i in range(5)] # All opened connections will automatically be released at the # end of the async with statement, even if attempts to open a # connection later in the list raise an exception. """ @staticmethod def _create_async_exit_wrapper(cm, cm_exit): return MethodType(cm_exit, cm) @staticmethod def _create_async_cb_wrapper(callback, /, *args, **kwds): async def _exit_wrapper(exc_type, exc, tb): await callback(*args, **kwds) return _exit_wrapper async def enter_async_context(self, cm): """Enters the supplied async context manager. If successful, also pushes its __aexit__ method as a callback and returns the result of the __aenter__ method. """ _cm_type = type(cm) _exit = _cm_type.__aexit__ result = await _cm_type.__aenter__(cm) self._push_async_cm_exit(cm, _exit) return result def push_async_exit(self, exit): """Registers a coroutine function with the standard __aexit__ method signature. Can suppress exceptions the same way __aexit__ method can. Also accepts any object with an __aexit__ method (registering a call to the method instead of the object itself). """ _cb_type = type(exit) try: exit_method = _cb_type.__aexit__ except AttributeError: # Not an async context manager, so assume it's a coroutine function self._push_exit_callback(exit, False) else: self._push_async_cm_exit(exit, exit_method) return exit # Allow use as a decorator def push_async_callback(self, callback, /, *args, **kwds): """Registers an arbitrary coroutine function and arguments. Cannot suppress exceptions. """ _exit_wrapper = self._create_async_cb_wrapper(callback, *args, **kwds) # We changed the signature, so using @wraps is not appropriate, but # setting __wrapped__ may still help with introspection. _exit_wrapper.__wrapped__ = callback self._push_exit_callback(_exit_wrapper, False) return callback # Allow use as a decorator async def aclose(self): """Immediately unwind the context stack.""" await self.__aexit__(None, None, None) def _push_async_cm_exit(self, cm, cm_exit): """Helper to correctly register coroutine function to __aexit__ method.""" _exit_wrapper = self._create_async_exit_wrapper(cm, cm_exit) self._push_exit_callback(_exit_wrapper, False) async def __aenter__(self): return self async def __aexit__(self, *exc_details): received_exc = exc_details[0] is not None # We manipulate the exception state so it behaves as though # we were actually nesting multiple with statements frame_exc = sys.exc_info()[1] def _fix_exception_context(new_exc, old_exc): # Context may not be correct, so find the end of the chain while 1: exc_context = new_exc.__context__ if exc_context is None or exc_context is old_exc: # Context is already set correctly (see issue 20317) return if exc_context is frame_exc: break new_exc = exc_context # Change the end of the chain to point to the exception # we expect it to reference new_exc.__context__ = old_exc # Callbacks are invoked in LIFO order to match the behaviour of # nested context managers suppressed_exc = False pending_raise = False while self._exit_callbacks: is_sync, cb = self._exit_callbacks.pop() try: if is_sync: cb_suppress = cb(*exc_details) else: cb_suppress = await cb(*exc_details) if cb_suppress: suppressed_exc = True pending_raise = False exc_details = (None, None, None) except: new_exc_details = sys.exc_info() # simulate the stack of exceptions by setting the context _fix_exception_context(new_exc_details[1], exc_details[1]) pending_raise = True exc_details = new_exc_details if pending_raise: try: # bare "raise exc_details[1]" replaces our carefully # set-up context fixed_ctx = exc_details[1].__context__ raise exc_details[1] except BaseException: exc_details[1].__context__ = fixed_ctx raise return received_exc and suppressed_exc class nullcontext(AbstractContextManager): """Context manager that does no additional processing. Used as a stand-in for a normal context manager, when a particular block of code is only sometimes used with a normal context manager: cm = optional_cm if condition else nullcontext() with cm: # Perform operation, using optional_cm if condition is True """ def __init__(self, enter_result=None): self.enter_result = enter_result def __enter__(self): return self.enter_result def __exit__(self, *excinfo): pass
Save
cmd:
run