
    9                        d Z ddlZddlZddlmZ ddlmZ g dZedgz  Z G d de      Z	 G d	 d
e	      Z
d Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Zej"                  d   dk\  Zerd Zd Znd Zd Z	 ddlmZ d Z G d de      Z G d de      Zy# e$ r eZY  w xY w) zAcontextlib2 - backports and enhancements to the contextlib module    N)dequewraps)contextmanagerclosingContextDecorator	ExitStackredirect_stdoutredirect_stderrsuppressContextStackc                   "    e Zd ZdZd Zd Zd Zy)r   zJA base class or mixin that enables context managers to work as decorators.c                 V    t        j                  dt               | j                         S )a  Returns the context manager used to actually wrap the call to the
        decorated function.

        The default implementation just returns *self*.

        Overriding this method allows otherwise one-shot context managers
        like _GeneratorContextManager to support use as decorators via
        implicit recreation.

        DEPRECATED: refresh_cm was never added to the standard library's
                    ContextDecorator API
        z2refresh_cm was never added to the standard library)warningswarnDeprecationWarning_recreate_cmselfs    'lib/third_party/contextlib2/__init__.py
refresh_cmzContextDecorator.refresh_cm   s%     	J(	*  ""    c                     | 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   s    r   r   zContextDecorator._recreate_cm"   s	     r   c                 2     t               fd       }|S )Nc                  `    j                         5   | i |cd d d        S # 1 sw Y   y xY wN)r   )argskwdsfuncr   s     r   innerz(ContextDecorator.__call__.<locals>.inner/   s(    ""$T*T* %$$s   $-r   )r   r    r!   s   `` r   __call__zContextDecorator.__call__.   s     	t	+ 
	+ r   N)__name__
__module____qualname____doc__r   r   r"   r   r   r   r   r      s    P#"
r   r   c                   (    e Zd ZdZd Zd Zd Zd Zy)_GeneratorContextManagerz%Helper for @contextmanager decorator.c                      ||i || _         |||c| _        | _        | _        t	        |dd       }|t        |       j                  }|| _        y )Nr&   )genr    r   r   getattrtyper&   )r   r    r   r   docs        r   __init__z!_GeneratorContextManager.__init__9   sR    &&*.d'	49didIt,;t*$$Cr   c                 d    | j                  | j                  | j                  | j                        S r   )	__class__r    r   r   r   s    r   r   z%_GeneratorContextManager._recreate_cmG   s#     ~~diiDII>>r   c                 ^    	 t        | j                        S # t        $ r t        d      w xY w)Nzgenerator didn't yield)nextr*   StopIterationRuntimeErrorr   s    r   	__enter__z"_GeneratorContextManager.__enter__M   s0    	9>! 	9788	9s    ,c                    |!	 t        | j                         t        d      | |       }	 | j                  j	                  |||       t        d      # t        $ r Y y w xY w# t        $ r}||ucY d }~S d }~wt        $ r(}||u rY d }~yt
        r|j                  |u rY d }~y d }~w t        j                         d   |ur Y y xY w)Nzgenerator didn't stopz#generator didn't stop after throw()F   )	r2   r*   r4   r3   throw_HAVE_EXCEPTION_CHAINING	__cause__sysexc_info)r   r,   value	tracebackexcs        r   __exit__z!_GeneratorContextManager.__exit__S   s    <<TXX ##:;;} tUI6"#HII !  ! ( %'' 	%<  ,0F 	 <<>!$E1 2sF   A (A% 	A"!A"%	C.A71C7CB&B&%B&&CN)r#   r$   r%   r&   r.   r   r5   r@   r   r   r   r(   r(   6   s    /?9(r   r(   c                 .     t                f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                      t        | |      S r   )r(   )r   r   r    s     r   helperzcontextmanager.<locals>.helper   s    'dD99r   r   )r    rC   s   ` r   r   r   ~   s     8 4[: :Mr   c                   "    e Zd ZdZd Zd Zd Zy)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                     || _         y r   thing)r   rG   s     r   r.   zclosing.__init__   s	    
r   c                     | j                   S r   rF   r   s    r   r5   zclosing.__enter__   s    zzr   c                 8    | j                   j                          y r   )rG   close)r   r<   s     r   r@   zclosing.__exit__   s    

r   Nr#   r$   r%   r&   r.   r5   r@   r   r   r   r   r      s     r   r   c                   "    e Zd ZdZd Zd Zd Zy)_RedirectStreamNc                      || _         g | _        y r   )_new_target_old_targets)r   
new_targets     r   r.   z_RedirectStream.__init__   s    %r   c                     | j                   j                  t        t        | j                               t        t        | j                  | j                         | j                  S r   )rP   appendr+   r;   _streamsetattrrO   r   s    r   r5   z_RedirectStream.__enter__   sC      dll!;<T\\4#3#34r   c                 j    t        t        | j                  | j                  j	                                y r   )rU   r;   rT   rP   popr   exctypeexcinstexctbs       r   r@   z_RedirectStream.__exit__   s!    T\\4#4#4#8#8#:;r   )r#   r$   r%   rT   r.   r5   r@   r   r   r   rM   rM      s    G
 
<r   rM   c                       e Zd ZdZdZy)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&   rT   r   r   r   r
   r
      s    
 Gr   r
   c                       e Zd ZdZdZy)r   zCContext manager for temporarily redirecting stderr to another file.stderrNr^   r   r   r   r   r      s
    MGr   r   c                   "    e Zd ZdZd Zd Zd Zy)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                     || _         y r   )_exceptions)r   
exceptionss     r   r.   zsuppress.__init__   s
    %r   c                      y r   r   r   s    r   r5   zsuppress.__enter__   s    r   c                 :    |d uxr t        || j                        S r   )
issubclassrc   rX   s       r   r@   zsuppress.__exit__   s!     d"Lz'4;K;K'LLr   NrK   r   r   r   r   r      s    &
Mr   r      c                       fd}|S )Nc                 L    	 | j                   }||u ry ||u r		 || _         y |} #r   )__context__)new_excold_excexc_context	frame_excs      r   _fix_exception_contextz3_make_context_fixer.<locals>._fix_exception_context  sB    %11')&+*B #*G & r   r   )ro   rp   s   ` r   _make_context_fixerrq     s    	* &%r   c                 \    	 | d   j                   }| d   # t        $ r | d   _          w xY w)Nr7   )rk   BaseException)exc_details	fixed_ctxs     r   _reraise_with_existing_contextrv     s@    	 $A22Ia.  	)2KN&	s    +c                     d S )Nc                      y r   r   )rl   rm   s     r   <lambda>z%_make_context_fixer.<locals>.<lambda>  s    r   r   )ro   s    r   rq   rq     s    ,,r   c                 &    | \  }}}t        d       y )Nz!raise exc_type, exc_value, exc_tb)exec)rt   exc_type	exc_valueexc_tbs       r   rv   rv   "  s    &1#)V12r   )InstanceTypec                 D    t        |       }|t        u r| j                  S |S r   )r,   r   r0   )objobj_types     r   	_get_typer   .  s"    9|#== r   c                   F    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zy)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                 "    t               | _        y r   )r   _exit_callbacksr   s    r   r.   zExitStack.__init__A  s    $wr   c                 f     t        |              }| j                  |_        t               | _        |S )z?Preserve the context stack by transferring it to a new instance)r,   r   r   )r   	new_stacks     r   pop_allzExitStack.pop_allD  s-    DJL	$($8$8	!$wr   c                 D    fd}|_         | j                  |       y)z:Helper to correctly register callbacks to __exit__ methodsc                       g|  S r   r   )rt   cmcm_exits    r   _exit_wrapperz.ExitStack._push_cm_exit.<locals>._exit_wrapperM  s    2,,,r   N)__self__push)r   r   r   r   s    `` r   _push_cm_exitzExitStack._push_cm_exitK  s    	-!#		- r   c                     t        |      }	 |j                  }| j                  ||       |S # t        $ r | j                  j                  |       Y |S w xY w)a  Registers a callback with the standard __exit__ method signature

        Can suppress exceptions the same way __exit__ methods can.

        Also accepts any object with an __exit__ method (registering a call
        to the method instead of the object itself)
        )r   r@   r   AttributeErrorr   rS   )r   exit_cb_typeexit_methods       r   r   zExitStack.pushR  s`     T?	2"++K
 t[1  	.  ''- 	.s   - $AAc                 J    fd}|_         | j                  |       S )z\Registers an arbitrary callback and arguments.

        Cannot suppress exceptions.
        c                      i  y r   r   )r|   r?   tbr   callbackr   s      r   r   z)ExitStack.callback.<locals>._exit_wrapperk  s    d#d#r   )__wrapped__r   )r   r   r   r   r   s    ``` r   r   zExitStack.callbackf  s#    
	$ %-!		- r   c                 z    t        |      }|j                  }|j                  |      }| j                  ||       |S )zEnters the supplied context manager

        If successful, also pushes its __exit__ method as a callback and
        returns the result of the __enter__ method.
        )r   r@   r5   r   )r   r   _cm_type_exitresults        r   enter_contextzExitStack.enter_contexts  s=     R=!!##B'2u%r   c                 *    | j                  ddd       y)z$Immediately unwind the context stackN)r@   r   s    r   rJ   zExitStack.close  s    dD$'r   c                     | S r   r   r   s    r   r5   zExitStack.__enter__  s    r   c                 \   |d   d u}t        j                         d   }t        |      }d}d}| j                  r3| j                  j	                         }	  || rd}d}d}| j                  r3|rt        |       |xr |S #  t        j                         } ||d   |d          d}|}Y KxY w)Nr   r7   FT)NNN)r;   r<   rq   r   rW   rv   )	r   rt   received_excro   rp   suppressed_excpending_raisecbnew_exc_detailss	            r   r@   zExitStack.__exit__  s    "1~T1 LLN1%	!4Y!? ""%%))+B
.{#%)N$)M"4K "" *;7..."%,,.&q'9;q>J $-s   B   )B+N)r#   r$   r%   r&   r.   r   r   r   r   r   rJ   r5   r@   r   r   r   r	   r	   5  s4    
'!((/r   r	   c                   4     e Zd ZdZ fdZd Zd Zd Z xZS )r   z+Backwards compatibility alias for ExitStackc                 ^    t        j                  dt               t        t        |           y )Nz*ContextStack has been renamed to ExitStack)r   r   r   superr   r.   )r   r0   s    r   r.   zContextStack.__init__  s"    B(	*lD*,r   c                 $    | j                  |      S r   )r   )r   r   s     r   register_exitzContextStack.register_exit  s    yy""r   c                 .     | j                   |g|i |S r   )r   )r   r   r   r   s       r   registerzContextStack.register  s    t}}X5555r   c                 "    | j                         S r   )r   r   s    r   preservezContextStack.preserve  s    ||~r   )	r#   r$   r%   r&   r.   r   r   r   __classcell__)r0   s   @r   r   r     s    5-
#6r   )r&   r;   r   collectionsr   	functoolsr   __all__objectr   r(   r   r   rM   r
   r   r   version_infor9   rq   rv   typesr   r   ImportErrorr,   r	   r   r   r   r   <module>r      s    G 
   = N %v %PE/ EPDf 2<f <$o  o Mv M> ++A.!3 & -
3
"m/ m/`9 y  Is   B3 3B=<B=