a future class similar to the one in pep 3148 all future wrapfuture isfuture import concurrent futures import contextvars import logging import sys from types import genericalias from import basefutures from import events from import exceptions from import formathelpers isfuture basefutures isfuture pending basefutures pending cancelled basefutures cancelled finished basefutures finished stackdebug logging debug 1 heavyduty debugging class future class variables serving as defaults for instance variables state pending result none exception none loop none sourcetraceback none cancelmessage none a saved cancellederror for later chaining as an exception context cancelledexc none this field is used for a dual purpose its presence is a marker to declare that a class implements the future protocol i e is intended to be ducktype compatible the value must also be notnone to enable a subclass to declare that it is not compatible by setting this to none it is set by iter below so that task step can tell the difference between await future oryield from future correct vs yield future incorrect asynciofutureblocking false logtraceback false def initself loopnone if loop is none self loop events geteventloop else self loop loop self callbacks if self loop getdebug self sourcetraceback formathelpers extractstack sys getframe1 def reprself return basefutures futurereprself def delself if not self logtraceback setexception was not called or result or exception has consumed the exception return exc self exception context message f self class name exception was never retrieved exception exc future self if self sourcetraceback context sourcetraceback self sourcetraceback self loop callexceptionhandlercontext classgetitem classmethodgenericalias property def logtracebackself return self logtraceback logtraceback setter def logtracebackself val if val raise valueerror logtraceback can only be set to false self logtraceback false def getloopself create the cancellederror to raise if the future is cancelled this should only be called once when handling a cancellation since it erases the saved context exception value remove the reference since we don t need this anymore cancel 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 internal ask the event loop to call all callbacks the callbacks are scheduled to be called as soon as possible also clears the callback list return true if the future was cancelled return self state cancelled don t implement running see http bugs python orgissue18699 def doneself return self state pending def resultself if self state cancelled exc self makecancellederror raise exc if self state finished raise exceptions invalidstateerror result is not ready self logtraceback false if self exception is not none raise self exception withtracebackself exceptiontb return self result def exceptionself if self state cancelled exc self makecancellederror raise exc if self state finished raise exceptions invalidstateerror exception is not set self logtraceback false return self exception def adddonecallbackself fn contextnone if self state pending self loop callsoonfn self contextcontext else if context is none context contextvars copycontext self callbacks appendfn context new method not in pep 3148 def removedonecallbackself fn filteredcallbacks f ctx for f ctx in self callbacks if f fn removedcount lenself callbacks lenfilteredcallbacks if removedcount self callbacks filteredcallbacks return removedcount socalled internal methods note no setrunningornotifycancel def setresultself result if self state pending raise exceptions invalidstateerrorf self state self r self result result self state finished self schedulecallbacks def setexceptionself exception if self state pending raise exceptions invalidstateerrorf self state self r if isinstanceexception type exception exception if typeexception is stopiteration raise typeerrorstopiteration interacts badly with generators and cannot be raised into a future self exception exception self exceptiontb exception traceback self state finished self schedulecallbacks self logtraceback true def awaitself if not self done self asynciofutureblocking true yield self this tells task to wait for completion if not self done raise runtimeerrorawait wasn t used with future return self result may raise too iter await make compatible with yield from needed for testing purposes pyfuture future def getloopfut tries to call future getloop if it s available otherwise fallbacks to using the old loop property try getloop fut getloop except attributeerror pass else return getloop return fut loop def setresultunlesscancelledfut result copy state from a future to a concurrent futures future assert source done if source cancelled concurrent cancel if not concurrent setrunningornotifycancel return exception source exception if exception is not none concurrent setexceptionconvertfutureexcexception else result source result concurrent setresultresult def copyfuturestatesource dest assert source done if dest cancelled return assert not dest done if source cancelled dest cancel else exception source exception if exception is not none dest setexceptionconvertfutureexcexception else result source result dest setresultresult def chainfuturesource destination if not isfuturesource and not isinstancesource concurrent futures future raise typeerror a future is required for source argument if not isfuturedestination and not isinstancedestination concurrent futures future raise typeerror a future is required for destination argument sourceloop getloopsource if isfuturesource else none destloop getloopdestination if isfuturedestination else none def setstatefuture other if isfuturefuture copyfuturestateother future else setconcurrentfuturestatefuture other def callcheckcanceldestination if destination cancelled if sourceloop is none or sourceloop is destloop source cancel else sourceloop callsoonthreadsafesource cancel def callsetstatesource if destination cancelled and destloop is not none and destloop isclosed return if destloop is none or destloop is sourceloop setstatedestination source else if destloop isclosed return destloop callsoonthreadsafesetstate destination source destination adddonecallbackcallcheckcancel source adddonecallbackcallsetstate def wrapfuturefuture loopnone cfuture is needed for tests heavy duty debugging 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 class variables serving as defaults for instance variables a saved cancellederror for later chaining as an exception context this field is used for a dual purpose its presence is a marker to declare that a class implements the future protocol i e is intended to be duck type compatible the value must also be not none to enable a subclass to declare that it is not compatible by setting this to none it is set by __iter__ below so that task _step can tell the difference between await future or yield from future correct vs yield future incorrect initialize the future the optional event_loop argument allows explicitly setting the event loop object used by the future if it s not provided the future uses the default event loop set_exception was not called or result or exception has consumed the exception return the event loop the future is bound to create the cancellederror to raise if the future is cancelled this should only be called once when handling a cancellation since it erases the saved context exception value remove the reference since we don t need this anymore cancel 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 internal ask the event loop to call all callbacks the callbacks are scheduled to be called as soon as possible also clears the callback list return true if the future was cancelled don t implement running see http bugs python org issue18699 return true if the future is done done means either that a result exception are available or that the future was cancelled return 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 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 add 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 new method not in pep 3148 remove all instances of a callback from the call when done list returns the number of callbacks removed so called internal methods note no set_running_or_notify_cancel mark the future done and set its result if the future is already done when this method is called raises invalidstateerror mark the future done and set an exception if the future is already done when this method is called raises invalidstateerror this tells task to wait for completion may raise too make compatible with yield from needed for testing purposes tries to call future get_loop if it s available otherwise fallbacks to using the old _loop property helper setting the result only if the future was not cancelled copy state from a future to a concurrent futures future internal helper to copy state from another future the other future may be a concurrent futures future chain 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 wrap concurrent futures future object _cfuture is needed for tests
__all__ = (
    'Future', 'wrap_future', 'isfuture',
)

import concurrent.futures
import contextvars
import logging
import sys
from types import GenericAlias

from . import base_futures
from . import events
from . import exceptions
from . import format_helpers


isfuture = base_futures.isfuture


_PENDING = base_futures._PENDING
_CANCELLED = base_futures._CANCELLED
_FINISHED = base_futures._FINISHED


STACK_DEBUG = logging.DEBUG - 1  


class Future:
    

    
    _state = _PENDING
    _result = None
    _exception = None
    _loop = None
    _source_traceback = None
    _cancel_message = None
    
    _cancelled_exc = None
    
    _asyncio_future_blocking = False

    __log_traceback = False

    def __init__(self, *, loop=None):
        
        if loop is None:
            self._loop = events.get_event_loop()
        else:
            self._loop = loop
        self._callbacks = []
        if self._loop.get_debug():
            self._source_traceback = format_helpers.extract_stack(
                sys._getframe(1))

    def __repr__(self):
        return base_futures._future_repr(self)

    def __del__(self):
        if not self.__log_traceback:
            return
        exc = self._exception
        context = {
            'message':
                f'{self.__class__.__name__} exception was never retrieved',
            'exception': exc,
            'future': self,
        }
        if self._source_traceback:
            context['source_traceback'] = self._source_traceback
        self._loop.call_exception_handler(context)

    __class_getitem__ = classmethod(GenericAlias)

    @property
    def _log_traceback(self):
        return self.__log_traceback

    @_log_traceback.setter
    def _log_traceback(self, val):
        if val:
            raise ValueError('_log_traceback can only be set to False')
        self.__log_traceback = False

    def get_loop(self):
        
        loop = self._loop
        if loop is None:
            raise RuntimeError("Future object is not initialized.")
        return loop

    def _make_cancelled_error(self):
        
        if self._cancelled_exc is not None:
            exc = self._cancelled_exc
            self._cancelled_exc = None
            return exc

        if self._cancel_message is None:
            exc = exceptions.CancelledError()
        else:
            exc = exceptions.CancelledError(self._cancel_message)
        exc.__context__ = self._cancelled_exc
        
        self._cancelled_exc = None
        return exc

    def cancel(self, msg=None):
        
        self.__log_traceback = False
        if self._state != _PENDING:
            return False
        self._state = _CANCELLED
        self._cancel_message = msg
        self.__schedule_callbacks()
        return True

    def __schedule_callbacks(self):
        
        callbacks = self._callbacks[:]
        if not callbacks:
            return

        self._callbacks[:] = []
        for callback, ctx in callbacks:
            self._loop.call_soon(callback, self, context=ctx)

    def cancelled(self):
        
        return self._state == _CANCELLED

    

    def done(self):
        
        return self._state != _PENDING

    def result(self):
        
        if self._state == _CANCELLED:
            exc = self._make_cancelled_error()
            raise exc
        if self._state != _FINISHED:
            raise exceptions.InvalidStateError('Result is not ready.')
        self.__log_traceback = False
        if self._exception is not None:
            raise self._exception.with_traceback(self._exception_tb)
        return self._result

    def exception(self):
        
        if self._state == _CANCELLED:
            exc = self._make_cancelled_error()
            raise exc
        if self._state != _FINISHED:
            raise exceptions.InvalidStateError('Exception is not set.')
        self.__log_traceback = False
        return self._exception

    def add_done_callback(self, fn, *, context=None):
        
        if self._state != _PENDING:
            self._loop.call_soon(fn, self, context=context)
        else:
            if context is None:
                context = contextvars.copy_context()
            self._callbacks.append((fn, context))

    

    def remove_done_callback(self, fn):
        
        filtered_callbacks = [(f, ctx)
                              for (f, ctx) in self._callbacks
                              if f != fn]
        removed_count = len(self._callbacks) - len(filtered_callbacks)
        if removed_count:
            self._callbacks[:] = filtered_callbacks
        return removed_count

    

    def set_result(self, result):
        
        if self._state != _PENDING:
            raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
        self._result = result
        self._state = _FINISHED
        self.__schedule_callbacks()

    def set_exception(self, exception):
        
        if self._state != _PENDING:
            raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
        if isinstance(exception, type):
            exception = exception()
        if type(exception) is StopIteration:
            raise TypeError("StopIteration interacts badly with generators "
                            "and cannot be raised into a Future")
        self._exception = exception
        self._exception_tb = exception.__traceback__
        self._state = _FINISHED
        self.__schedule_callbacks()
        self.__log_traceback = True

    def __await__(self):
        if not self.done():
            self._asyncio_future_blocking = True
            yield self  
        if not self.done():
            raise RuntimeError("await wasn't used with future")
        return self.result()  

    __iter__ = __await__  


_PyFuture = Future


def _get_loop(fut):
    
    
    try:
        get_loop = fut.get_loop
    except AttributeError:
        pass
    else:
        return get_loop()
    return fut._loop


def _set_result_unless_cancelled(fut, result):
    
    if fut.cancelled():
        return
    fut.set_result(result)


def _convert_future_exc(exc):
    exc_class = type(exc)
    if exc_class is concurrent.futures.CancelledError:
        return exceptions.CancelledError(*exc.args)
    elif exc_class is concurrent.futures.TimeoutError:
        return exceptions.TimeoutError(*exc.args)
    elif exc_class is concurrent.futures.InvalidStateError:
        return exceptions.InvalidStateError(*exc.args)
    else:
        return exc


def _set_concurrent_future_state(concurrent, source):
    
    assert source.done()
    if source.cancelled():
        concurrent.cancel()
    if not concurrent.set_running_or_notify_cancel():
        return
    exception = source.exception()
    if exception is not None:
        concurrent.set_exception(_convert_future_exc(exception))
    else:
        result = source.result()
        concurrent.set_result(result)


def _copy_future_state(source, dest):
    
    assert source.done()
    if dest.cancelled():
        return
    assert not dest.done()
    if source.cancelled():
        dest.cancel()
    else:
        exception = source.exception()
        if exception is not None:
            dest.set_exception(_convert_future_exc(exception))
        else:
            result = source.result()
            dest.set_result(result)


def _chain_future(source, destination):
    
    if not isfuture(source) and not isinstance(source,
                                               concurrent.futures.Future):
        raise TypeError('A future is required for source argument')
    if not isfuture(destination) and not isinstance(destination,
                                                    concurrent.futures.Future):
        raise TypeError('A future is required for destination argument')
    source_loop = _get_loop(source) if isfuture(source) else None
    dest_loop = _get_loop(destination) if isfuture(destination) else None

    def _set_state(future, other):
        if isfuture(future):
            _copy_future_state(other, future)
        else:
            _set_concurrent_future_state(future, other)

    def _call_check_cancel(destination):
        if destination.cancelled():
            if source_loop is None or source_loop is dest_loop:
                source.cancel()
            else:
                source_loop.call_soon_threadsafe(source.cancel)

    def _call_set_state(source):
        if (destination.cancelled() and
                dest_loop is not None and dest_loop.is_closed()):
            return
        if dest_loop is None or dest_loop is source_loop:
            _set_state(destination, source)
        else:
            if dest_loop.is_closed():
                return
            dest_loop.call_soon_threadsafe(_set_state, destination, source)

    destination.add_done_callback(_call_check_cancel)
    source.add_done_callback(_call_set_state)


def wrap_future(future, *, loop=None):
    
    if isfuture(future):
        return future
    assert isinstance(future, concurrent.futures.Future), \
        f'concurrent.futures.Future is expected, got {future!r}'
    if loop is None:
        loop = events.get_event_loop()
    new_future = loop.create_future()
    _chain_future(future, new_future)
    return new_future


try:
    import _asyncio
except ImportError:
    pass
else:
    
    Future = _CFuture = _asyncio.Future