
    raW                         d Z dZdZddlZddlmZ ddlZddlZddl	m
Z
 e
j                  Zej                  j                  dkD  Z G d	 d
e      Z G d de      Z G d de      Z G d de      Zd Zd Zd Zd Zd Zy)z-Small framework for asynchronous programming.z%Sebastian Heinlein <devel@glatzor.de>)DeferredAlreadyCalledDeferredDeferredExceptiondeferinline_callbacksreturn_value    Nwraps   )version   c                       e Zd ZdZd Zy)_DefGen_Returnz5Exception to return a result from an inline callback.c                     || _         y N)value)selfr   s     0/usr/lib/python3/dist-packages/defer/__init__.py__init__z_DefGen_Return.__init__S   s	    
    N)__name__
__module____qualname____doc__r    r   r   r   r   Q   s
    ?r   r   c                       e Zd ZdZy)r   z+The Deferred is already running a callback.N)r   r   r   r   r   r   r   r   r   W   s    5r   r   c                   $    e Zd ZdZddZd Zd Zy)r   zAllows to defer exceptions.Nc                     || _         || _        || _        t        |t              r|j
                  | _         || _        y|r|s(t        j                         \  | _         | _        | _        yy)a  Return a new DeferredException instance.

        If type, value and traceback are not specified the infotmation
        will be retreieved from the last caught exception:

        >>> try:
        ...     raise Exception("Test")
        ... except:
        ...     deferred_exc = DeferredException()
        >>> deferred_exc.raise_exception()
        Traceback (most recent call last):
            ...
        Exception: Test

        Alternatively you can set the exception manually:

        >>> exception = Exception("Test 2")
        >>> deferred_exc = DeferredException(exception)
        >>> deferred_exc.raise_exception()
        Traceback (most recent call last):
            ...
        Exception: Test 2
        N)typer   	traceback
isinstance	Exception	__class__sysexc_info)r   r   r   r    s       r   r   zDeferredException.__init__^   sW    0 	
"dI&DIDJU47LLN1DItz4> #r   c                     t         r%| j                  j                  | j                        | j	                  | j                        j                  | j                        )zRaise the stored exception.)PY3Kr   with_tracebackr    r   r   s    r   raise_exceptionz!DeferredException.raise_exception   s@    **++DNN;;))DJJ'66t~~FFr   c                 f    |D ]  }t        | j                  |      s|c S  | j                          y)a8  Check if the stored exception is a subclass of one of the
        provided exception classes. If this is the case return the
        matching exception class. Otherwise raise the stored exception.

        >>> exc = DeferredException(SystemError())
        >>> exc.catch(Exception) # Will catch the exception and return it
        <class 'Exception'>
        >>> exc.catch(OSError)   # Won't catch and raise the stored exception
        Traceback (most recent call last):
            ...
        SystemError

        This method can be used in errbacks of a Deferred:

        >>> def dummy_errback(deferred_exception):
        ...     '''Error handler for OSError'''
        ...     deferred_exception.catch(OSError)
        ...     return "catched"

        The above errback can handle an OSError:

        >>> deferred = Deferred()
        >>> deferred.add_errback(dummy_errback)
        >>> deferred.errback(OSError())
        >>> deferred.result
        'catched'

        But fails to handle a SystemError:

        >>> deferred2 = Deferred()
        >>> deferred2.add_errback(dummy_errback)
        >>> deferred2.errback(SystemError())
        >>> deferred2.result                             #doctest: +ELLIPSIS
        <defer.DeferredException object at 0x...>
        >>> deferred2.result.value
        SystemError()
        N)
issubclassr   r*   )r   errorserrs      r   catchzDeferredException.catch   s5    L  	C$))S)
	 	r   )NNN)r   r   r   r   r   r*   r/   r   r   r   r   r   [   s    %CBG)r   r   c                   L    e Zd ZdZd Z	 	 	 ddZd Zd ZddZddZ	d	 Z
d
 Zy)r   a  The Deferred allows to chain callbacks.

    There are two type of callbacks: normal callbacks and errbacks, which
    handle an exception in a normal callback.

    The callbacks are processed in pairs consisting of a normal callback
    and an errback. A normal callback will return its result to the
    callback of the next pair.  If an exception occurs, it will be handled
    by the errback of the next pair. If an errback doesn't raise an error
    again, the callback of the next pair will be called with the return
    value of the errback. Otherwise the exception of the errback will be
    returned to the errback of the next pair::

        CALLBACK1      ERRBACK1
         |     \       /     |
     result failure  result failure
         |       \   /       |
         |        \ /        |
         |         X         |
         |        / \        |
         |       /   \       |
         |      /     \      |
        CALLBACK2      ERRBACK2
         |     \       /     |
     result failure  result failure
         |       \   /       |
         |        \ /        |
         |         X         |
         |        / \        |
         |       /   \       |
         |      /     \      |
        CALLBACK3      ERRBACK3
      c                 J    g | _         g | _        d| _        d| _        d| _        y)zReturn a new Deferred instance.FN)	callbackserrbackscalledpaused_runningr)   s    r   r   zDeferred.__init__   s%    r   Nc                 `   t        |t        j                  j                        sJ |&t        |t        j                  j                        sJ |t        }| j
                  j                  ||xs g |xs i f|xs t        |xs g |xs i ff       | j                  r| j                          yy)aA  Add a pair of callables (function or method) to the callback and
        errback chain.

        Keyword arguments:
        callback -- the next chained challback
        errback -- the next chained errback
        callback_args -- list of additional arguments for the callback
        callback_kwargs -- dict of additional arguments for the callback
        errback_args -- list of additional arguments for the errback
        errback_kwargs -- dict of additional arguments for the errback

        In the following example the first callback pairs raises an
        exception that is catched by the errback of the second one and
        processed by the third one.

        >>> def callback(previous):
        ...     '''Return the previous result.'''
        ...     return "Got: %s" % previous
        >>> def callback_raise(previous):
        ...     '''Fail and raise an exception.'''
        ...     raise Exception("Test")
        >>> def errback(error):
        ...     '''Recover from an exception.'''
        ...     #error.catch(Exception)
        ...     return "catched"
        >>> deferred = Deferred()
        >>> deferred.callback("start")
        >>> deferred.result
        'start'
        >>> deferred.add_callbacks(callback_raise, errback)
        >>> deferred.result                             #doctest: +ELLIPSIS
        <defer.DeferredException object at 0x...>
        >>> deferred.add_callbacks(callback, errback)
        >>> deferred.result
        'catched'
        >>> deferred.add_callbacks(callback, errback)
        >>> deferred.result
        'Got: catched'
        N)	r!   collectionsabcCallable_passthroughr2   appendr4   _next)r   callbackerrbackcallback_argscallback_kwargserrback_argserrback_kwargss          r   add_callbackszDeferred.add_callbacks   s    T (KOO$<$<===*Wkoo6N6N"OOO?"G - 5" / 7B 9 !( 9L , 4 . 62 89 	: ;;JJL r   c                 6    | j                  t        |||       y)a~  Add a callable (function or method) to the errback chain only.

        If there isn't any exception the result will be passed through to
        the callback of the next pair.

        The first argument is the callable instance followed by any
        additional argument that will be passed to the errback.

        The errback method will get the most recent DeferredException and
        and any additional arguments that was specified in add_errback.

        If the errback can catch the exception it can return a value that
        will be passed to the next callback in the chain. Otherwise the
        errback chain will not be processed anymore.

        See the documentation of defer.DeferredException.catch for
        further information.

        >>> def catch_error(deferred_error, ignore=False):
        ...     if ignore:
        ...         return "ignored"
        ...     deferred_error.catch(Exception)
        ...     return "catched"
        >>> deferred = Deferred()
        >>> deferred.errback(SystemError())
        >>> deferred.add_errback(catch_error, ignore=True)
        >>> deferred.result
        'ignored'
        )rB   rC   NrD   r;   r   funcargskwargss       r   add_errbackzDeferred.add_errback  s     < 	<D*0 	 	2r   c                 6    | j                  |t        ||       y)a  Add a callable (function or method) to the callback chain only.

        An error would be passed through to the next errback.

        The first argument is the callable instance followed by any
        additional argument that will be passed to the callback.

        The callback method will get the result of the previous callback
        and any additional arguments that was specified in add_callback.

        >>> def callback(previous, counter=False):
        ...     if counter:
        ...         return previous + 1
        ...     return previous
        >>> deferred = Deferred()
        >>> deferred.add_callback(callback, counter=True)
        >>> deferred.callback(1)
        >>> deferred.result
        2
        )r@   rA   NrF   rG   s       r   add_callbackzDeferred.add_callback5  s     * 	4T+1 	 	3r   c                     | j                   r
t               |st               }n9t        |t              s)t        |t              sJ t        |j
                  |d      }d| _         || _        | j                          y)a  Start processing the errorback chain starting with the
        provided exception or DeferredException.

        If an exception is specified it will be wrapped into a
        DeferredException. It will be send to the first errback or stored 
        as finally result if not any further errback has been specified yet.

        >>> deferred = Deferred()
        >>> deferred.errback(Exception("Test Error"))
        >>> deferred.result                             #doctest: +ELLIPSIS
        <defer.DeferredException object at 0x...>
        >>> deferred.result.raise_exception()
        Traceback (most recent call last):
            ...
        Exception: Test Error
        NT)r4   r   r   r!   r"   r#   resultr=   )r   errors     r   r?   zDeferred.errbackM  sc    " ;;'))%'EE#45eY///%eooudCE

r   c                 l    | j                   r
t               d| _         || _        | j                          y)aO  Start processing the callback chain starting with the
        provided result.

        It will be send to the first callback or stored as finally
        one if not any further callback has been specified yet.

        >>> deferred = Deferred()
        >>> deferred.callback("done")
        >>> deferred.result
        'done'
        TN)r4   r   rO   r=   r   rO   s     r   r>   zDeferred.callbacki  s+     ;;'))

r   c                 Z    || _         d| _        | j                  r| j                          yy)z7Continue processing the Deferred with the given result.FN)rO   r5   r4   r=   rR   s     r   	_continuezDeferred._continue{  s%    ;;JJL r   c                    | j                   s| j                  ry| j                  r| j                  j                  d      }|t	        | j
                  t                 \  }}}	  || j
                  g|i || _        d| _         t	        | j
                  t              r@| j
                  j                  | j                  | j                         | j                  dk(   n| j                  rt	        | j
                  t              rTt        j                  | j
                  j                  | j
                  j                  | j
                  j                         yy#  t               | _        Y xY w# d| _         w xY w)zProcess the next callback.Nr   FT)r6   r5   r2   popr!   rO   r   r   rD   rT   r$   
excepthookr   r   r    )r   	next_pairr>   rI   rJ   s        r   r=   zDeferred._next  s!   ==DKKnn**1-I%.z$++:K0M &N"HdF&&t{{DTDVD !&$++x0
 ))$..$..It#' nn* dkk#45 NN4;;++T[[->->;;002 62/1 %s   #E E.,E1 1	E:)NNNNNr   )r   r   r   r   r   rD   rK   rM   r?   r>   rT   r=   r   r   r   r   r      s=     
D /3:>8<5n2B308$r   r   c                     t        | t        j                  j                        sJ 	  | |i |}t        |t
              r|S t               }|j                  |       |S #  t	               }Y =xY w)a  Invoke the given function that may or not may be a Deferred.

    If the return object of the function call is a Deferred return, it.
    Otherwise wrap it into a Deferred.

    >>> defer(lambda x: x, 10)                 #doctest: +ELLIPSIS
    <defer.Deferred object at 0x...>

    >>> deferred = defer(lambda x: x, "done")
    >>> deferred.result
    'done'

    >>> deferred = Deferred()
    >>> defer(lambda: deferred) == deferred
    True
    )r!   r8   r9   r:   r   r   r>   )rH   rI   rJ   rO   deferreds        r   r   r     sl    " dKOO44555%t&v& &(#zHfO%"$s   A A-c                     | S r   r   )args    r   r;   r;     s    Jr   c                     t        |       )a  
    Return val from a inline_callbacks generator.

    Note: this is currently implemented by raising an exception
    derived from BaseException.  You might want to change any
    'except:' clauses to an 'except Exception:' clause so as not to
    catch this exception.

    Also: while this function currently will work when called from
    within arbitrary functions called from within the generator, do
    not rely upon this behavior.
    )r   )vals    r   r   r     s     
r   c                    ddg	 	 t        | t              }|rt        r7| j                  j	                  | j
                        }j                  |      } nUj                  | j                  | j                        j	                  | j
                              } nj                  |       } t        | t0              r4fd}
| j3                  |
|
       d	   rd
d	<   S d   } dd	<   dd<   # t        $ r j                  d       cY S t        $ r>}t        j                         d   j                  }r|j                  }|j                  r|j                  j                  r|}|j                  j                  r#|j                  }|j                  j                  r#|j                  j                   j"                  }|j$                  }	t'        j(                  d|j                  j                   j*                  d|j                  j                   j*                  dt,        ||	       j                  |j                         cY d}~S d}~w j/                          cY S xY w)z
    See inlineCallbacks.
    TNr   r   zreturnValue() in z	 causing zX to exit: returnValue should only be invoked by functions decorated with inlineCallbacksc                 @    d   rdd<   | d<   y t        |        y )Nr   Fr   )_inline_callbacks)resrZ   genwaitings    r   	gotResultz$_inline_callbacks.<locals>.gotResult  s(    1:!&GAJ!$GAJ%c39r   r   F)r!   r   r'   r   r(   r    throwr   sendStopIterationr>   r   r$   r%   tb_nexttb_framef_codeco_filename	tb_linenowarningswarn_explicitco_nameDeprecationWarningr?   r   rD   )rO   rc   rZ   
is_failureexcepr.   appCodeTraceultimateTracefilenamelinenore   rd   s    ``        @r   ra   ra     s$    G 9	#F,=>J"LL778H8HIE YYu-F YYv{{6<<'@'O'OPVP`P`'abF&)b fh':   I6qz #
QZF
 GAJGAJe   	d#O '	 <<>!,44L  ,33 ##(<(<(D(D
 !-#++33$1$9$9M $++33(1188DD&00&& &..55==$--44<<	>
 '&: cii(O	Os,   B$C3 3I,	I,BI&B'II,I,c                 .     t                fd       }|S )a  inline_callbacks helps you write Deferred-using code that looks like a
    regular sequential function. For example::

        def thingummy():
            thing = yield makeSomeRequestResultingInDeferred()
            print thing #the result! hoorj!
        thingummy = inline_callbacks(thingummy)

    When you call anything that results in a Deferred, you can simply yield it;
    your generator will automatically be resumed when the Deferred's result is
    available. The generator will be sent the result of the Deferred with the
    'send' method on generators, or if the result was a failure, 'throw'.

    Your inline_callbacks-enabled generator will return a Deferred object, which
    will result in the return value of the generator (or will fail with a
    failure object if your generator raises an unhandled exception). Note that
    you can't use return result to return a value; use return_value(result)
    instead. Falling off the end of the generator, or simply using return
    will cause the Deferred to have a result of None.

    The Deferred returned from your deferred generator may errback if your
    generator raised an exception::

        def thingummy():
            thing = yield makeSomeRequestResultingInDeferred()
            if thing == 'I love Twisted':
                # will become the result of the Deferred
                return_value('TWISTED IS GREAT!')
            else:
                # will trigger an errback
                raise Exception('DESTROY ALL LIFE')
        thingummy = inline_callbacks(thingummy)
    c                  :    t        d  | i |t                     S r   )ra   r   )rI   rJ   rH   s     r   unwind_generatorz*inline_callbacks.<locals>.unwind_generatorS  s     tT'<V'<hjIIr   r	   )rH   rz   s   ` r   r   r   1  s$    D 4[J Jr   )r   
__author____all__collections.abcr8   	functoolsr
   r$   rn    r   VERSION__version__version_infomajorr'   BaseExceptionr   r"   r   objectr   r   r   r;   r   ra   r   r   r   r   <module>r      s    4x 6
8   
  oo
!] 6I 6T Tnnv n`8_B%r   