+e?@s?dZdddddgZddlZddlZddlZddlZddlZdd lm Z dd lm Z d Z d Z d Z ejjjZejjZejjZejdZGdddeZGdddZGdddZddZddZddZddZddddZdS)z.A Future class similar to the one in PEP 3148.CancelledError TimeoutErrorInvalidStateErrorFuture wrap_futureN)compat)eventsZPENDINGZ CANCELLEDZFINISHEDc@seZdZdZdS)rz+The operation is not allowed in this state.N)__name__ __module__ __qualname____doc__rr4/opt/alt/python34/lib64/python3.4/asyncio/futures.pyrs c@sLeZdZdZdZddZdd Zd d Zd d ZdS)_TracebackLoggera Helper to log a traceback upon destruction if not cleared. This solves a nasty problem with Futures and Tasks that have an exception set: if nobody asks for the exception, the exception is never logged. This violates the Zen of Python: 'Errors should never pass silently. Unless explicitly silenced.' However, we don't want to log the exception as soon as set_exception() is called: if the calling code is written properly, it will get the exception and handle it properly. But we *do* want to log it if result() or exception() was never called -- otherwise developers waste a lot of time wondering why their buggy code fails silently. An earlier attempt added a __del__() method to the Future class itself, but this backfired because the presence of __del__() prevents garbage collection from breaking cycles. A way out of this catch-22 is to avoid having a __del__() method on the Future class itself, but instead to have a reference to a helper object with a __del__() method that logs the traceback, where we ensure that the helper object doesn't participate in cycles, and only the Future has a reference to it. The helper object is added when set_exception() is called. When the Future is collected, and the helper is present, the helper object is also collected, and its __del__() method will log the traceback. When the Future's result() or exception() method is called (and a helper object is present), it removes the helper object, after calling its clear() method to prevent it from logging. One downside is that we do a fair amount of work to extract the traceback from the exception, even when it is never logged. It would seem cheaper to just store the exception object, but that references the traceback, which references stack frames, which may reference the Future, which references the _TracebackLogger, and then the _TracebackLogger would be included in a cycle, which is what we're trying to avoid! As an optimization, we don't immediately format the exception; we only do the work when activate() is called, which call is delayed until after all the Future's callbacks have run. Since usually a Future has at least one callback (typically set by 'yield from') and usually that callback extracts the callback, thereby removing the need to format the exception. PS. I don't claim credit for this solution. I first heard of it in a discussion about closing files when they are collected. loopsource_tracebackexctbcCs.|j|_|j|_||_d|_dS)N)_loopr_source_tracebackrrr)selffuturerrrr__init__Us   z_TracebackLogger.__init__cCsC|j}|dk r?d|_tj|j||j|_ndS)N)r tracebackformat_exception __class__ __traceback__r)rrrrractivate[s    z_TracebackLogger.activatecCsd|_d|_dS)N)rr)rrrrclearbs z_TracebackLogger.clearcCs|jrd}|jrTdjtj|j}|d7}|d|j7}n|dj|jj7}|jji|d6ndS)Nz*Future/Task exception was never retrieved z0Future/Task created at (most recent call last): z%s message)rrjoinr format_listrstriprcall_exception_handler)rmsgsrcrrr__del__fs   z_TracebackLogger.__del__N)zloopzsource_tracebackzexcztb) r r r r __slots__rrrr(rrrrr!s 0   rc@s*eZdZdZeZdZdZdZdZ dZ dZ dZ ddddZ ddZd d Zd d Zejrd dZnddZddZddZddZddZddZddZddZdd Zd!d"Zd#d$Zejr&eZ ndS)%raThis class is *almost* compatible with concurrent.futures.Future. Differences: - result() and exception() do not take a timeout argument and raise an exception when the future isn't done yet. - Callbacks registered with add_done_callback() are always called via the event loop's call_soon_threadsafe(). - This class is not compatible with the wait() and as_completed() methods in the concurrent.futures package. (In Python 3.4 or later we may be able to unify the implementations.) NFrcCsa|dkrtj|_n ||_g|_|jjr]tjtjd|_ ndS)zInitialize the future. The optional event_loop argument allows to explicitly set the event loop object used by the future. If it's not provided, the future uses the default event loop. Nr) r Zget_event_loopr _callbacksZ get_debugr extract_stacksys _getframer)rrrrrrs    zFuture.__init__cCs|j}t|}|s$d}ndd}|dkrO||d}nq|dkrdj||d||d}n<|dkrdj||d|d||d }nd |S) Nr cSstj|fS)N)r Z_format_callback_source)callbackrrr format_cbsz,Future.__format_callbacks..format_cbrrz{}, {}z{}, <{} more>, {}zcb=[%s])r*lenformat)rcbsizer/rrrZ__format_callbackss      ) zFuture.__format_callbackscCs|jjg}|jtkrw|jdk rL|jdj|jqwtj|j}|jdj|n|j r|j|j n|j r|j d}|jd|d|dfn|S)Nzexception={!r}z result={}rzcreated at %s:%srr1) _statelower _FINISHED _exceptionappendr3reprlibrepr_resultr*_Future__format_callbacksr)rinforesultZframerrr _repr_infos   "zFuture._repr_infocCs)|j}d|jjdj|fS)Nz<%s %s> )rArr r")rr?rrr__repr__s zFuture.__repr__cCsh|js dS|j}id|jjd6|d6|d6}|jrT|j|d:s z/Future.remove_done_callback..N)r*r2)rrOZfiltered_callbacksZ removed_countr)rOrremove_done_callback5s zFuture.remove_done_callbackcCsM|jtkr-tdj|j|n||_t|_|jdS)zMark the future done and set its result. If the future is already done when this method is called, raises InvalidStateError. z{}: {!r}N)r6rGrr3r=r8rI)rr@rrr set_resultBs   zFuture.set_resultcCs|jtkr-tdj|j|nt|trH|}n||_t|_|jt j ryd|_ n(t |||_ |jj|j jdS)zMark the future done and set an exception. If the future is already done when this method is called, raises InvalidStateError. z{}: {!r}TN)r6rGrr3 isinstancetyper9r8rIrPY34rErrNrrKr)rrDrrr set_exceptionNs      zFuture.set_exceptionccs?|jsd|_|Vn|js5td|jS)NTz"yield from wasn't used with future)rM _blockingAssertionErrorr@)rrrr__iter__cs   zFuture.__iter__)!r r r r rGr6r=r9rrrZrErNrr>rArCrrXr(rJrIrLrMr@rDrPrTrUrYr\ZPY35Z __await__rrrrrqs8              cCs!|jrdS|j|dS)z?Helper setting the result only if the future was not cancelled.N)rLrU)Zfutr@rrr_set_result_unless_cancelledns r]cCs|jst|jr+|jn|js;dS|j}|dk rc|j|n|j}|j|dS)z8Copy state from a future to a concurrent.futures.Future.N) rMr[rLrJZset_running_or_notify_cancelrDrYr@rU) concurrentsourcerDr@rrr_set_concurrent_future_stateus      r`cCs|jst|jr"dS|j s5t|jrN|jnA|j}|dk rv|j|n|j}|j|dS)zqInternal helper to copy state from another Future. The other Future may be a concurrent.futures.Future. N)rMr[rLrJrDrYr@rU)r_destrDr@rrr_copy_future_states      rbcstttjjfs*tdntttjjfsTtdnttrljndttrjndddfdd}fdd }j|j|dS) aChain two futures so that when one completes, so does the other. The result (or exception) of source will be copied to destination. If destination is cancelled, source gets cancelled too. Compatible with both asyncio.Future and concurrent.futures.Future. z(A future is required for source argumentz-A future is required for destination argumentNcSs0t|trt||n t||dS)N)rVrrbr`)rotherrrr _set_statesz!_chain_future.._set_statecsH|jrDdks$kr1jqDjjndS)N)rLrJcall_soon_threadsafe) destination) dest_loopr_ source_looprr_call_check_cancels  z)_chain_future.._call_check_cancelcs?dkskr(|nj|dS)N)re)r_)rdrgrfrhrr_call_set_statesz&_chain_future.._call_set_state)rVrr^futures TypeErrorrrP)r_rfrirjr)rdrgrfr_rhr _chain_futures  rmrcCs]t|tr|St|tjjs=tdj|td|}t|||S)z&Wrap concurrent.futures.Future object.z/concurrent.futures.Future is expected, got {!r}r)rVrr^rkr[r3rm)rrZ new_futurerrrrs )r __all__Zconcurrent.futures._baser^Zloggingr;r,rr rr rGrHr8rkZ_baseErrorrrDEBUGZ STACK_DEBUGrrrr]r`rbrmrrrrrs2         P    %