B M��j�`� @s^dZddlZddlZddlZddlmZddlmZddddd d d d d dddg ZGdd �d ej �Z Gdd �d ej �Z Gdd �d e �Z Gdd�d�ZGdd�dee e �ZGdd�dee �Zdd�Zdd�ZGdd�de �ZGdd�de �ZGdd�de�ZGd d�de�ZGd!d�de �ZGd"d#�d#�ZGd$d �d ee �ZGd%d �d ee �ZGd&d�de �ZdS)'z4Utilities for with-statement contexts. See PEP 343.�N)�deque)�wraps�asynccontextmanager�contextmanager�closing� nullcontext�AbstractContextManager�AbstractAsyncContextManager�AsyncExitStack�ContextDecorator� ExitStack�redirect_stdout�redirect_stderr�suppressc@s2eZdZdZdd�Zejdd��Zedd��Z dS) rz,An abstract base class for context managers.cCs|S)z0Return `self` upon entering the runtime context.�)�selfrr�//opt/alt/python37/lib64/python3.7/contextlib.py� __enter__sz AbstractContextManager.__enter__cCsdS)z9Raise any exception triggered within the runtime context.Nr)r�exc_type� exc_value� tracebackrrr�__exit__szAbstractContextManager.__exit__cCs|tkrt�|dd�StS)Nrr)r�_collections_abc�_check_methods�NotImplemented)�cls�Crrr�__subclasshook__sz'AbstractContextManager.__subclasshook__N) �__name__� __module__� __qualname__�__doc__r�abc�abstractmethodr� classmethodrrrrrrsc@s2eZdZdZdd�Zejdd��Zedd��Z dS) r z9An abstract base class for asynchronous context managers.c�s|S)z0Return `self` upon entering the runtime context.r)rrrr� __aenter__&sz&AbstractAsyncContextManager.__aenter__c�sdS)z9Raise any exception triggered within the runtime context.Nr)rrrrrrr� __aexit__*sz%AbstractAsyncContextManager.__aexit__cCs|tkrt�|dd�StS)Nr%r&)r rrr)rrrrrr/sz,AbstractAsyncContextManager.__subclasshook__N) rrr r!r%r"r#r&r$rrrrrr "sc@s eZdZdZdd�Zdd�ZdS)r zJA base class or mixin that enables context managers to work as decorators.cCs|S)a6Return 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. r)rrrr� _recreate_cm:s zContextDecorator._recreate_cmcst����fdd��}|S)Nc s���� �||�SQRXdS)N)r')�args�kwds)�funcrrr�innerGs z(ContextDecorator.__call__.<locals>.inner)r)rr*r+r)r*rr�__call__FszContextDecorator.__call__N)rrr r!r'r,rrrrr 7s c@seZdZdZdd�ZdS)�_GeneratorContextManagerBasezBShared functionality for @contextmanager and @asynccontextmanager.cCsJ|||�|_||||_|_|_t|dd�}|dkr@t|�j}||_dS)Nr!)�genr*r(r)�getattr�typer!)rr*r(r)�docrrr�__init__Qs    z%_GeneratorContextManagerBase.__init__N)rrr r!r2rrrrr-Nsr-c@s(eZdZdZdd�Zdd�Zdd�ZdS) �_GeneratorContextManagerz%Helper for @contextmanager decorator.cCs|�|j|j|j�S)N)� __class__r*r(r))rrrrr'esz%_GeneratorContextManager._recreate_cmcCs:|`|`|`y t|j�Stk r4td�d�YnXdS)Nzgenerator didn't yield)r(r)r*�nextr.� StopIteration� RuntimeError)rrrrrks   z"_GeneratorContextManager.__enter__c Cs�|dkr6yt|j�Wntk r*dSXtd��n�|dkrD|�}y|j�|||�Wn�tk r~}z||k Sd}~XYnftk r�}z(||kr�dS|tkr�|j|kr�dS�Wdd}~XYn"t��d|kr�dS�YnXtd��dS)NFzgenerator didn't stop�z#generator didn't stop after throw())r5r.r6r7�throw� __cause__�sys�exc_info)rr0�valuer�excrrrrts.  z!_GeneratorContextManager.__exit__N)rrr r!r'rrrrrrr3`s r3c@s eZdZdZdd�Zdd�ZdS)�_AsyncGeneratorContextManagerz Helper for @asynccontextmanager.c�s4y|j��IdHStk r.td�d�YnXdS)Nzgenerator didn't yield)r.� __anext__�StopAsyncIterationr7)rrrrr%�sz(_AsyncGeneratorContextManager.__aenter__c �s|dkr<y|j��IdHWntk r0dSXtd��n�|dkrJ|�}y"|j�|||�IdHtd��Wn�tk r�}z||k Sd}~XYnztk r�}z.||kr�dSt|ttf�r�|j|kr�dS�Wdd}~XYn0tk �r }z||k �r��Wdd}~XYnXdS)Nzgenerator didn't stopz$generator didn't stop after athrow()F) r.r@rAr7�athrow� isinstancer6r:� BaseException)r�typr=rr>rrrr&�s.    z'_AsyncGeneratorContextManager.__aexit__N)rrr r!r%r&rrrrr?�sr?cst���fdd��}|S)a�@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> cs t�||�S)N)r3)r(r))r*rr�helper�szcontextmanager.<locals>.helper)r)r*rFr)r*rr�scst���fdd��}|S)a�@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> cs t�||�S)N)r?)r(r))r*rrrFsz#asynccontextmanager.<locals>.helper)r)r*rFr)r*rr�sc@s(eZdZdZdd�Zdd�Zdd�ZdS) ra2Context 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() cCs ||_dS)N)�thing)rrGrrrr2%szclosing.__init__cCs|jS)N)rG)rrrrr'szclosing.__enter__cGs|j��dS)N)rG�close)rr<rrrr)szclosing.__exit__N)rrr r!r2rrrrrrrsc@s(eZdZdZdd�Zdd�Zdd�ZdS)�_RedirectStreamNcCs||_g|_dS)N)� _new_target� _old_targets)r� new_targetrrrr21sz_RedirectStream.__init__cCs*|j�tt|j��tt|j|j�|jS)N)rK�appendr/r;�_stream�setattrrJ)rrrrr6sz_RedirectStream.__enter__cCstt|j|j���dS)N)rOr;rNrK�pop)r�exctype�excinst�exctbrrrr;sz_RedirectStream.__exit__)rrr rNr2rrrrrrrI-srIc@seZdZdZdZdS)r aAContext 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) �stdoutN)rrr r!rNrrrrr ?s c@seZdZdZdZdS)rzCContext manager for temporarily redirecting stderr to another file.�stderrN)rrr r!rNrrrrrOsc@s(eZdZdZdd�Zdd�Zdd�ZdS) ra?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 cGs ||_dS)N)� _exceptions)r� exceptionsrrrr2`szsuppress.__init__cCsdS)Nr)rrrrrcszsuppress.__enter__cCs|dk ot||j�S)N)� issubclassrV)rrQrRrSrrrrfs zsuppress.__exit__N)rrr r!r2rrrrrrrUs c@sbeZdZdZedd��Zedd��Zdd�Zdd �Zd d �Z d d �Z dd�Z dd�Z ddd�Z dS)�_BaseExitStackz.A base class for ExitStack and AsyncExitStack.cs��fdd�}|S)Ncs��|||�S)Nr)rr>�tb)�cm�cm_exitrr� _exit_wrapperxsz:_BaseExitStack._create_exit_wrapper.<locals>._exit_wrapperr)r[r\r]r)r[r\r�_create_exit_wrappervsz#_BaseExitStack._create_exit_wrappercs�^�����fdd�}|S)Ncs����dS)Nr)rr>rZ)r(�callbackr)rrr]sz8_BaseExitStack._create_cb_wrapper.<locals>._exit_wrapperr)r(r)r]r)r(r_r)r�_create_cb_wrapper|sz!_BaseExitStack._create_cb_wrappercCs t�|_dS)N)r�_exit_callbacks)rrrrr2�sz_BaseExitStack.__init__cCst|��}|j|_t�|_|S)z@Preserve the context stack by transferring it to a new instance.)r0rar)r� new_stackrrr�pop_all�s z_BaseExitStack.pop_allcCsBt|�}y |j}Wntk r0|�|�YnX|�||�|S)aRegisters 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). )r0r�AttributeError�_push_exit_callback� _push_cm_exit)r�exit�_cb_type� exit_methodrrr�push�s   z_BaseExitStack.pushcCs(t|�}|j}|�|�}|�||�|S)z�Enters the supplied context manager. If successful, also pushes its __exit__ method as a callback and returns the result of the __enter__ method. )r0rrrf)rr[�_cm_type�_exit�resultrrr� enter_context�s   z_BaseExitStack.enter_contextcOs|t|�dkr|^}}}n>|s&td��n0d|krB|�d�}|^}}ntdt|�d��|j|f|�|�}||_|�|�|S)z\Registers an arbitrary callback and arguments. Cannot suppress exceptions. �zBdescriptor 'callback' of '_BaseExitStack' object needs an argumentr_z8callback expected at least 1 positional argument, got %dr8)�len� TypeErrorrPr`� __wrapped__re)r(r)rr_r]rrrr_�s      z_BaseExitStack.callbackcCs"|�||�}||_|�|d�dS)z;Helper to correctly register callbacks to __exit__ methods.TN)r^�__self__re)rr[r\r]rrrrf�s z_BaseExitStack._push_cm_exitTcCs|j�||f�dS)N)rarM)rr_�is_syncrrrre�sz"_BaseExitStack._push_exit_callbackN)T)rrr r!� staticmethodr^r`r2rcrjrnr_rfrerrrrrYss  rYc@s(eZdZdZdd�Zdd�Zdd�ZdS) r a�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. cCs|S)Nr)rrrrr�szExitStack.__enter__c s�|ddk }t��d��fdd�}d}d}x`|jr�|j��\}}y||�rXd}d}d}Wq.t��}||d|d�d}|}Yq.Xq.W|r�y|dj} |d�Wn tk r�| |d_�YnX|o�|S)Nrr8cs8x,|j}||krdS|dks$|�kr&P|}qW||_dS)N)� __context__)�new_exc�old_exc� exc_context)� frame_excrr�_fix_exception_context�sz2ExitStack.__exit__.<locals>._fix_exception_contextFT)NNN)r;r<rarPrvrD) r� exc_details� received_excr{�suppressed_exc� pending_raisert�cb�new_exc_details� fixed_ctxr)rzrr�s2      zExitStack.__exit__cCs|�ddd�dS)z%Immediately unwind the context stack.N)r)rrrrrHszExitStack.closeN)rrr r!rrrHrrrrr �s 1c@s`eZdZdZedd��Zedd��Zdd�Zdd �Zd d �Z d d �Z dd�Z dd�Z dd�Z dS)r a�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. cs��fdd�}|S)Nc�s��|||�IdHS)Nr)rr>rZ)r[r\rrr]'sz@AsyncExitStack._create_async_exit_wrapper.<locals>._exit_wrapperr)r[r\r]r)r[r\r�_create_async_exit_wrapper%sz)AsyncExitStack._create_async_exit_wrappercs�^�����fdd�}|S)Nc�s����IdHdS)Nr)rr>rZ)r(r_r)rrr].sz>AsyncExitStack._create_async_cb_wrapper.<locals>._exit_wrapperr)r(r)r]r)r(r_r)r�_create_async_cb_wrapper+sz'AsyncExitStack._create_async_cb_wrapperc�s.t|�}|j}|�|�IdH}|�||�|S)z�Enters the supplied async context manager. If successful, also pushes its __aexit__ method as a callback and returns the result of the __aenter__ method. N)r0r&r%�_push_async_cm_exit)rr[rkrlrmrrr�enter_async_context2s  z"AsyncExitStack.enter_async_contextcCsDt|�}y |j}Wn tk r2|�|d�YnX|�||�|S)a#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). F)r0r&rdrer�)rrgrhrirrr�push_async_exit>s  zAsyncExitStack.push_async_exitcOs~t|�dkr|^}}}n>|s&td��n0d|krB|�d�}|^}}ntdt|�d��|j|f|�|�}||_|�|d�|S)zfRegisters an arbitrary coroutine function and arguments. Cannot suppress exceptions. rozMdescriptor 'push_async_callback' of 'AsyncExitStack' object needs an argumentr_zCpush_async_callback expected at least 1 positional argument, got %dr8F)rprqrPr�rrre)r(r)rr_r]rrr�push_async_callbackPs      z"AsyncExitStack.push_async_callbackc�s|�ddd�IdHdS)z%Immediately unwind the context stack.N)r&)rrrr�acloseiszAsyncExitStack.aclosecCs"|�||�}||_|�|d�dS)zLHelper to correctly register coroutine function to __aexit__ method.FN)r�rsre)rr[r\r]rrrr�ms z"AsyncExitStack._push_async_cm_exitc�s|S)Nr)rrrrr%tszAsyncExitStack.__aenter__c �s�|ddk }t��d��fdd�}d}d}xx|jr�|j��\}}y0|rR||�}n||�IdH}|rpd}d}d}Wq.t��} || d|d�d}| }Yq.Xq.W|r�y|dj} |d�Wn tk r�| |d_�YnX|o�|S)Nrr8cs8x,|j}||krdS|dks$|�kr&P|}qW||_dS)N)rv)rwrxry)rzrrr{}sz8AsyncExitStack.__aexit__.<locals>._fix_exception_contextFT)NNN)r;r<rarPrvrD) rr|r}r{r~rrtr�� cb_suppressr�r�r)rzrr&ws8       zAsyncExitStack.__aexit__N)rrr r!rur�r�r�r�r�r�r�r%r&rrrrr s    c@s*eZdZdZd dd�Zdd�Zdd�ZdS) raOContext 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 NcCs ||_dS)N)� enter_result)rr�rrrr2�sznullcontext.__init__cCs|jS)N)r�)rrrrr�sznullcontext.__enter__cGsdS)Nr)r�excinforrrr�sznullcontext.__exit__)N)rrr r!r2rrrrrrr�s  )r!r"r;r� collectionsr� functoolsr�__all__�ABCrr �objectr r-r3r?rrrrIr rrrYr r rrrrr�<module>s<    B -!!`E