3 \> @s dZddddddgZddlZddlZddlZddlZd d lmZd d lm Z d d lm Z ej Z ej Z ej Z ejZejZejZejZejd ZGd ddZGdddZeZddZddZddZddZddddZy ddlZWnek rYn XejZZdS)z.A Future class similar to the one in PEP 3148.CancelledError TimeoutErrorInvalidStateErrorFuture wrap_futureisfutureN) base_futures)compat)eventsc@s4eZdZdZdZddZdd 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)selffuturerr/usr/lib64/python3.6/futures.py__init__Rsz_TracebackLogger.__init__cCs,|j}|dk r(d|_tj|j||j|_dS)N)r tracebackformat_exception __class__ __traceback__r)rrrrractivateXs  z_TracebackLogger.activatecCsd|_d|_dS)N)rr)rrrrclear_sz_TracebackLogger.clearcCsb|jr^d}|jr:djtj|j}|d7}|d|j7}|dj|jj7}|jjd|idS)Nz*Future/Task exception was never retrieved z0Future/Task created at (most recent call last): z%s message)rrjoinr format_listrstripr call_exception_handler)rmsgsrcrrr__del__csz_TracebackLogger.__del__N)r rrr) __name__ __module__ __qualname____doc__ __slots__rrrr&rrrrr s 0r c@seZdZdZeZdZdZdZdZ dZ dZ ddddZ e jZddZejrRd d Zd d Zd dZddZddZddZddZddZddZddZddZdd ZejreZ dS)!ra,This class is *almost* compatible with concurrent.futures.Future. Differences: - This class is not thread-safe. - 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(). - 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.) NF)r cCs@|dkrtj|_n||_g|_|jjr )rr'r _repr_info)rrrr__repr__szFuture.__repr__cCsD|js dS|j}d|jj||d}|jr4|j|d<|jj|dS)Nz %s exception was never retrieved)r exceptionrr)_log_traceback _exceptionrr'rrr#)rrcontextrrrr&s zFuture.__del__cCs&d|_|jtkrdSt|_|jdS)zCancel the future and schedule callbacks. If the future is already done or cancelled, return False. Otherwise, change the future's state to cancelled, schedule the callbacks and return True. FT)r5_state_PENDING _CANCELLED_schedule_callbacks)rrrrcancels  z Future.cancelcCsD|jdd}|sdSg|jdd<x|D]}|jj||q*WdS)zInternal: Ask the event loop to call all callbacks. The callbacks are scheduled to be called as soon as possible. Also clears the callback list. N)r-r call_soon)rZ callbackscallbackrrrr;s  zFuture._schedule_callbackscCs |jtkS)z(Return True if the future was cancelled.)r8r:)rrrr cancelledszFuture.cancelledcCs |jtkS)zReturn True if the future is done. Done means either that a result / exception are available, or that the future was cancelled. )r8r9)rrrrdonesz Future.donecCs<|jtkrt|jtkr tdd|_|jdk r6|j|jS)aReturn the result this future represents. If the future has been cancelled, raises CancelledError. If the future's result isn't yet available, raises InvalidStateError. If the future is done and has an exception set, this exception is raised. zResult is not ready.FN)r8r:r _FINISHEDrr5r6_result)rrrrresults   z Future.resultcCs,|jtkrt|jtkr tdd|_|jS)a&Return the exception that was set on this future. The exception (or None if no exception was set) is returned only if the future is done. If the future has been cancelled, raises CancelledError. If the future isn't done yet, raises InvalidStateError. zException is not set.F)r8r:rrArr5r6)rrrrr4s   zFuture.exceptioncCs*|jtkr|jj||n |jj|dS)zAdd a callback to be run when the future becomes done. The callback is called with a single argument - the future object. If the future is already done when this is called, the callback is scheduled with call_soon. N)r8r9rr=r-append)rfnrrradd_done_callbacks zFuture.add_done_callbackcs<fdd|jD}t|jt|}|r8||jdd<|S)z}Remove all instances of a callback from the "call when done" list. Returns the number of callbacks removed. csg|]}|kr|qSrr).0f)rErr sz/Future.remove_done_callback..N)r-len)rrEZfiltered_callbacksZ removed_countr)rErremove_done_callbacks zFuture.remove_done_callbackcCs4|jtkrtdj|j|||_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)r8r9rformatrBrAr;)rrCrrr set_result s  zFuture.set_resultcCs|jtkrtdj|j|t|tr,|}t|tkr@td||_t |_|j t j rbd|_ nt|||_|jj|jjdS)zMark the future done and set an exception. If the future is already done when this method is called, raises InvalidStateError. z{}: {!r}zPStopIteration interacts badly with generators and cannot be raised into a FutureTN)r8r9rrL isinstancetype StopIteration TypeErrorr6rAr;r PY34r5r Z _tb_loggerrr=r)rr4rrr set_exception,s    zFuture.set_exceptionccs|jsd|_|V|jS)NT)r@_asyncio_future_blockingrC)rrrr__iter__DszFuture.__iter__)!r'r(r)r*r9r8rBr6rrrTr5rr Z_future_repr_infor2r3r rRr&r<r;r?r@rCr4rFrKrMrSrUZPY35 __await__rrrrrns4   cCs|jr dS|j|dS)z?Helper setting the result only if the future was not cancelled.N)r?rM)ZfutrCrrr_set_result_unless_cancelledSsrWcCsN|jr|j|jsdS|j}|dk r8|j|n|j}|j|dS)z8Copy state from a future to a concurrent.futures.Future.N)r?r<Zset_running_or_notify_cancelr4rSrCrM) concurrentsourcer4rCrrr_set_concurrent_future_stateZs rZcCsP|jr dS|jr|jn.|j}|dk r:|j|n|j}|j|dS)zqInternal helper to copy state from another Future. The other Future may be a concurrent.futures.Future. N)r?r<r4rSrCrM)rYdestr4rCrrr_copy_future_stateis  r\cst r"ttjj r"tdt rDttjj rDtdtrRjndtrdjndddfdd}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 argumentNcSs"t|rt||n t||dS)N)rr\rZ)rotherrrr _set_states z!_chain_future.._set_statecs2|jr.dkskr"jn jjdS)N)r?r<call_soon_threadsafe) destination) dest_looprY source_looprr_call_check_cancels z)_chain_future.._call_check_cancelcsJjrdk rjrdSdks,kr8|nj|dS)N)r?Z is_closedr_)rY)r^rar`rbrr_call_set_states  z&_chain_future.._call_set_state)rrNrXZfuturesrrQrrF)rYr`rcrdr)r^rar`rYrbr _chain_future}s   re)r cCs2t|r |S|dkrtj}|j}t|||S)z&Wrap concurrent.futures.Future object.N)rr r,Z create_futurere)rr Z new_futurerrrrs )r*__all__concurrent.futuresrXZloggingr/rrr r r rrrrr9r:rADEBUGZ STACK_DEBUGr rZ _PyFuturerWrZr\rerZ_asyncio ImportErrorZ_CFuturerrrrs>     Pc*