a
    jCi0`  ã                   @   sZ  d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	m
Z
 g d¢ZG dd„ dejƒZG d	d
„ d
ejƒZG dd„ deƒZG dd„ dƒZG dd„ deeeƒZG dd„ deeƒZdd„ Zdd„ ZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd „ d eƒZG d!d"„ d"ƒZG d#d$„ d$eeƒZG d%d&„ d&eeƒZG d'd(„ d(eƒZdS ))z4Utilities for with-statement contexts.  See PEP 343.é    N)Údeque©Úwraps)Ú
MethodTypeÚGenericAlias)ÚasynccontextmanagerÚcontextmanagerÚclosingÚnullcontextÚAbstractContextManagerÚAbstractAsyncContextManagerÚAsyncExitStackÚContextDecoratorÚ	ExitStackÚredirect_stdoutÚredirect_stderrÚsuppressc                   @   s:   e Zd ZdZeeƒZdd„ Zej	dd„ ƒZ
edd„ ƒZdS )	r   z,An abstract base class for context managers.c                 C   s   | S ©z0Return `self` upon entering the runtime context.© ©Úselfr   r   ú&/usr/local/lib/python3.9/contextlib.pyÚ	__enter__   s    z AbstractContextManager.__enter__c                 C   s   dS ©z9Raise any exception triggered within the runtime context.Nr   ©r   Úexc_typeÚ	exc_valueÚ	tracebackr   r   r   Ú__exit__   s    zAbstractContextManager.__exit__c                 C   s   | t u rt |dd¡S tS )Nr   r   )r   Ú_collections_abcÚ_check_methodsÚNotImplemented©ÚclsÚCr   r   r   Ú__subclasshook__   s    z'AbstractContextManager.__subclasshook__N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Úclassmethodr   Ú__class_getitem__r   ÚabcÚabstractmethodr   r%   r   r   r   r   r      s   
r   c                   @   s:   e Zd ZdZeeƒZdd„ Zej	dd„ ƒZ
edd„ ƒZdS )	r   z9An abstract base class for asynchronous context managers.c                 Ã   s   | S r   r   r   r   r   r   Ú
__aenter__+   s    z&AbstractAsyncContextManager.__aenter__c                 Ã   s   dS r   r   r   r   r   r   Ú	__aexit__/   s    z%AbstractAsyncContextManager.__aexit__c                 C   s   | t u rt |dd¡S tS )Nr.   r/   )r   r   r    r!   r"   r   r   r   r%   4   s
    ÿz,AbstractAsyncContextManager.__subclasshook__N)r&   r'   r(   r)   r*   r   r+   r.   r,   r-   r/   r%   r   r   r   r   r   %   s   
r   c                   @   s    e Zd ZdZdd„ Zdd„ ZdS )r   zJA base class or mixin that enables context managers to work as decorators.c                 C   s   | S )a6  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.
        r   r   r   r   r   Ú_recreate_cm?   s    
zContextDecorator._recreate_cmc                    s   t ˆ ƒ‡ ‡fdd„ƒ}|S )Nc                     s:   ˆ  ¡ � ˆ | i |¤ŽW  d   ƒ S 1 s,0    Y  d S ©N)r0   ©ÚargsÚkwds©Úfuncr   r   r   ÚinnerL   s    
z(ContextDecorator.__call__.<locals>.innerr   )r   r6   r7   r   r5   r   Ú__call__K   s    zContextDecorator.__call__N)r&   r'   r(   r)   r0   r8   r   r   r   r   r   <   s   r   c                   @   s    e Zd ZdZdd„ Zdd„ ZdS )Ú_GeneratorContextManagerBasezBShared functionality for @contextmanager and @asynccontextmanager.c                 C   sN   ||i |¤Ž| _ |||  | _| _| _t|dd ƒ}|d u rDt| ƒj}|| _d S )Nr)   )Úgenr6   r3   r4   ÚgetattrÚtyper)   )r   r6   r3   r4   Údocr   r   r   Ú__init__V   s    
z%_GeneratorContextManagerBase.__init__c                 C   s   |   | j| j| j¡S r1   )Ú	__class__r6   r3   r4   r   r   r   r   r0   d   s    z)_GeneratorContextManagerBase._recreate_cmN)r&   r'   r(   r)   r>   r0   r   r   r   r   r9   S   s   r9   c                   @   s    e Zd ZdZdd„ Zdd„ ZdS )Ú_GeneratorContextManagerz%Helper for @contextmanager decorator.c                 C   s:   | ` | `| `zt| jƒW S  ty4   tdƒd ‚Y n0 d S ©Nzgenerator didn't yield)r3   r4   r6   Únextr:   ÚStopIterationÚRuntimeErrorr   r   r   r   r   r   s
    z"_GeneratorContextManager.__enter__c              
   C   s   |d u r6zt | jƒ W n ty*   Y dS 0 tdƒ‚næ|d u rD|ƒ }z| j |||¡ W nº ty„ } z||uW  Y d }~S d }~0  tyà } zF||u r¨W Y d }~dS t|tƒrÊ|j|u rÊW Y d }~dS ‚ W Y d }~n<d }~0  t�y } z||u� rü‚ W Y d }~dS d }~0 0 tdƒ‚d S )NFúgenerator didn't stopz#generator didn't stop after throw())rB   r:   rC   rD   ÚthrowÚ
isinstanceÚ	__cause__ÚBaseException©r   ÚtypÚvaluer   Úexcr   r   r   r   {   s4    
ÿþ
z!_GeneratorContextManager.__exit__N)r&   r'   r(   r)   r   r   r   r   r   r   r@   k   s   	r@   c                   @   s    e Zd ZdZdd„ Zdd„ ZdS )Ú_AsyncGeneratorContextManagerz*Helper for @asynccontextmanager decorator.c                 Ã   s@   | ` | `| `z| j ¡ I d H W S  ty:   tdƒd ‚Y n0 d S rA   )r3   r4   r6   r:   Ú	__anext__ÚStopAsyncIterationrD   r   r   r   r   r.   °   s
    z(_AsyncGeneratorContextManager.__aenter__c              
   Ã   s4  |d u r>z| j  ¡ I d H  W n ty0   Y dS 0 tdƒ‚� nò|d u rL|ƒ }z| j  |||¡I d H  W nÀ ty’ } z||uW  Y d }~S d }~0  t� yô } zJ||u r¸W Y d }~dS t|ttfƒrÞ|j|u rÞW Y d }~dS ‚ W Y d }~n<d }~0  t�y& } z||u�r‚ W Y d }~dS d }~0 0 tdƒ‚d S )NFrE   z$generator didn't stop after athrow())	r:   rO   rP   rD   ÚathrowrG   rC   rH   rI   rJ   r   r   r   r/   ¹   s4    ÿþ
z'_AsyncGeneratorContextManager.__aexit__N)r&   r'   r(   r)   r.   r/   r   r   r   r   rN   ¬   s   	rN   c                    s   t ˆ ƒ‡ fdd„ƒ}|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>
    c                     s   t ˆ | |ƒS r1   )r@   r2   ©r6   r   r   Úhelper  s    zcontextmanager.<locals>.helperr   ©r6   rS   r   rR   r   r   ê   s    r   c                    s   t ˆ ƒ‡ fdd„ƒ}|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>
    c                     s   t ˆ | |ƒS r1   )rN   r2   rR   r   r   rS   &  s    z#asynccontextmanager.<locals>.helperr   rT   r   rR   r   r     s    r   c                   @   s(   e Zd ZdZdd„ Zdd„ Zdd„ ZdS )	r	   a2  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()

    c                 C   s
   || _ d S r1   ©Úthing)r   rV   r   r   r   r>   =  s    zclosing.__init__c                 C   s   | j S r1   rU   r   r   r   r   r   ?  s    zclosing.__enter__c                 G   s   | j  ¡  d S r1   )rV   Úclose)r   Úexc_infor   r   r   r   A  s    zclosing.__exit__N©r&   r'   r(   r)   r>   r   r   r   r   r   r   r	   ,  s   r	   c                   @   s(   e Zd ZdZdd„ Zdd„ Zdd„ ZdS )Ú_RedirectStreamNc                 C   s   || _ g | _d S r1   )Ú_new_targetÚ_old_targets)r   Z
new_targetr   r   r   r>   I  s    z_RedirectStream.__init__c                 C   s*   | j  tt| jƒ¡ tt| j| jƒ | jS r1   )r\   Úappendr;   ÚsysÚ_streamÚsetattrr[   r   r   r   r   r   N  s    z_RedirectStream.__enter__c                 C   s   t t| j| j ¡ ƒ d S r1   )r`   r^   r_   r\   Úpop©r   ZexctypeZexcinstZexctbr   r   r   r   S  s    z_RedirectStream.__exit__)r&   r'   r(   r_   r>   r   r   r   r   r   r   rZ   E  s   rZ   c                   @   s   e Zd ZdZdZdS )r   aA  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)
    ÚstdoutN©r&   r'   r(   r)   r_   r   r   r   r   r   W  s   r   c                   @   s   e Zd ZdZdZdS )r   zCContext manager for temporarily redirecting stderr to another file.ÚstderrNrd   r   r   r   r   r   g  s   r   c                   @   s(   e Zd ZdZdd„ Zdd„ Zdd„ ZdS )	r   a?  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
    c                 G   s
   || _ d S r1   )Ú_exceptions)r   Z
exceptionsr   r   r   r>   x  s    zsuppress.__init__c                 C   s   d S r1   r   r   r   r   r   r   {  s    zsuppress.__enter__c                 C   s   |d uot || jƒS r1   )Ú
issubclassrf   rb   r   r   r   r   ~  s    
zsuppress.__exit__NrY   r   r   r   r   r   m  s   
r   c                   @   sb   e Zd ZdZedd„ ƒZedd„ ƒZdd„ Zdd	„ Zd
d„ Z	dd„ Z
dd„ Zdd„ Zddd„ZdS )Ú_BaseExitStackz.A base class for ExitStack and AsyncExitStack.c                 C   s
   t || ƒS r1   ©r   ©ÚcmÚcm_exitr   r   r   Ú_create_exit_wrapperŽ  s    z#_BaseExitStack._create_exit_wrapperc                   s   ‡ ‡‡fdd„}|S )Nc                    s   ˆˆ i ˆ¤Ž d S r1   r   ©r   rM   Útb©r3   Úcallbackr4   r   r   Ú_exit_wrapper”  s    z8_BaseExitStack._create_cb_wrapper.<locals>._exit_wrapperr   ©rq   r3   r4   rr   r   rp   r   Ú_create_cb_wrapper’  s    z!_BaseExitStack._create_cb_wrapperc                 C   s   t ƒ | _d S r1   )r   Ú_exit_callbacksr   r   r   r   r>   ˜  s    z_BaseExitStack.__init__c                 C   s   t | ƒƒ }| j|_tƒ | _|S )z@Preserve the context stack by transferring it to a new instance.)r<   ru   r   )r   Z	new_stackr   r   r   Úpop_all›  s    
z_BaseExitStack.pop_allc                 C   s@   t |ƒ}z
|j}W n ty.   |  |¡ Y n0 |  ||¡ |S )a  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).
        )r<   r   ÚAttributeErrorÚ_push_exit_callbackÚ_push_cm_exit©r   ÚexitZ_cb_typeZexit_methodr   r   r   Úpush¢  s    	
z_BaseExitStack.pushc                 C   s(   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.
        )r<   r   r   ry   ©r   rk   Z_cm_typeÚ_exitÚresultr   r   r   Úenter_context¶  s
    
z_BaseExitStack.enter_contextc                O   s,   | j |g|¢R i |¤Ž}||_|  |¡ |S )z\Registers an arbitrary callback and arguments.

        Cannot suppress exceptions.
        )rt   Ú__wrapped__rx   ©r   rq   r3   r4   rr   r   r   r   rq   Ä  s    
z_BaseExitStack.callbackc                 C   s   |   ||¡}|  |d¡ dS )z;Helper to correctly register callbacks to __exit__ methods.TN)rm   rx   ©r   rk   rl   rr   r   r   r   ry   Ñ  s    z_BaseExitStack._push_cm_exitTc                 C   s   | j  ||f¡ d S r1   )ru   r]   )r   rq   Úis_syncr   r   r   rx   Ö  s    z"_BaseExitStack._push_exit_callbackN)T)r&   r'   r(   r)   Ústaticmethodrm   rt   r>   rv   r|   r€   rq   ry   rx   r   r   r   r   rh   ‹  s   

rh   c                   @   s(   e Zd ZdZdd„ Zdd„ Zdd„ ZdS )	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.
    c                 C   s   | S r1   r   r   r   r   r   r   æ  s    zExitStack.__enter__c           
         sÔ   |d d u}t  ¡ d ‰ ‡ fdd„}d}d}| jr’| j ¡ \}}|sHJ ‚z||Ž r^d}d}d}W q,   t  ¡ }||d |d ƒ d}|}Y q,0 q,|rÌz|d j}	|d ‚W n tyÊ   |	|d _‚ Y n0 |oÒ|S )Nr   é   c                    s4   | j }|d u s||u rd S |ˆ u r$q*|} q || _ d S r1   ©Ú__context__©Znew_excZold_excZexc_context©Z	frame_excr   r   Ú_fix_exception_contextï  s    z2ExitStack.__exit__.<locals>._fix_exception_contextFT©NNN©r^   rX   ru   ra   rˆ   rI   )
r   Úexc_detailsÚreceived_excr‹   Úsuppressed_excÚpending_raiser„   ÚcbÚnew_exc_detailsÚ	fixed_ctxr   rŠ   r   r   é  s4    

zExitStack.__exit__c                 C   s   |   ddd¡ dS ©z%Immediately unwind the context stack.N)r   r   r   r   r   rW     s    zExitStack.closeN)r&   r'   r(   r)   r   r   rW   r   r   r   r   r   Û  s   
1r   c                   @   s`   e Zd ZdZedd„ ƒZedd„ ƒZdd„ Zdd	„ Zd
d„ Z	dd„ Z
dd„ Zdd„ Zdd„ ZdS )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.
    c                 C   s
   t || ƒS r1   ri   rj   r   r   r   Ú_create_async_exit_wrapper-  s    z)AsyncExitStack._create_async_exit_wrapperc                   s   ‡ ‡‡fdd„}|S )Nc                 “   s   ˆˆ i ˆ¤ŽI d H  d S r1   r   rn   rp   r   r   rr   3  s    z>AsyncExitStack._create_async_cb_wrapper.<locals>._exit_wrapperr   rs   r   rp   r   Ú_create_async_cb_wrapper1  s    z'AsyncExitStack._create_async_cb_wrapperc                 Ã   s.   t |ƒ}|j}| |¡I dH }|  ||¡ |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)r<   r/   r.   Ú_push_async_cm_exitr}   r   r   r   Úenter_async_context7  s
    z"AsyncExitStack.enter_async_contextc                 C   sB   t |ƒ}z
|j}W n ty0   |  |d¡ Y n0 |  ||¡ |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)r<   r/   rw   rx   r˜   rz   r   r   r   Úpush_async_exitC  s    
zAsyncExitStack.push_async_exitc                O   s.   | j |g|¢R i |¤Ž}||_|  |d¡ |S )zfRegisters an arbitrary coroutine function and arguments.

        Cannot suppress exceptions.
        F)r—   r�   rx   r‚   r   r   r   Úpush_async_callbackU  s    z"AsyncExitStack.push_async_callbackc                 Ã   s   |   ddd¡I dH  dS r•   )r/   r   r   r   r   Úacloseb  s    zAsyncExitStack.aclosec                 C   s   |   ||¡}|  |d¡ dS )zLHelper to correctly register coroutine function to __aexit__
        method.FN)r–   rx   rƒ   r   r   r   r˜   f  s    z"AsyncExitStack._push_async_cm_exitc                 Ã   s   | S r1   r   r   r   r   r   r.   l  s    zAsyncExitStack.__aenter__c                 ‡   sä   |d d u}t  ¡ d ‰ ‡ fdd„}d}d}| jr¢| j ¡ \}}z0|rP||Ž }n||Ž I d H }|rnd}d}d}W q,   t  ¡ }	||	d |d ƒ d}|	}Y q,0 q,|rÜz|d j}
|d ‚W n tyÚ   |
|d _‚ Y n0 |oâ|S )Nr   r†   c                    s4   | j }|d u s||u rd S |ˆ u r$q*|} q || _ d S r1   r‡   r‰   rŠ   r   r   r‹   u  s    z8AsyncExitStack.__aexit__.<locals>._fix_exception_contextFTrŒ   r�   )r   rŽ   r�   r‹   r�   r‘   r„   r’   Zcb_suppressr“   r”   r   rŠ   r   r/   o  s8    


zAsyncExitStack.__aexit__N)r&   r'   r(   r)   r…   r–   r—   r™   rš   r›   rœ   r˜   r.   r/   r   r   r   r   r      s   

r   c                   @   s*   e Zd ZdZd	dd„Zdd„ Zdd„ ZdS )
r
   aO  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
    Nc                 C   s
   || _ d S r1   ©Úenter_result)r   rž   r   r   r   r>   °  s    znullcontext.__init__c                 C   s   | j S r1   r�   r   r   r   r   r   ³  s    znullcontext.__enter__c                 G   s   d S r1   r   )r   Zexcinfor   r   r   r   ¶  s    znullcontext.__exit__)NrY   r   r   r   r   r
   ¥  s   

r
   )r)   r,   r^   r   Úcollectionsr   Ú	functoolsr   Útypesr   r   Ú__all__ÚABCr   r   Úobjectr   r9   r@   rN   r   r   r	   rZ   r   r   r   rh   r   r   r
   r   r   r   r   Ú<module>   s>   
ýAÿ>!!PE 