2013-10-17 17:40:50 -03:00
|
|
|
"""A Future class similar to the one in PEP 3148."""
|
|
|
|
|
2016-10-28 13:52:37 -03:00
|
|
|
__all__ = ['CancelledError', 'TimeoutError', 'InvalidStateError',
|
|
|
|
'Future', 'wrap_future', 'isfuture']
|
2013-10-17 17:40:50 -03:00
|
|
|
|
2016-10-28 13:52:37 -03:00
|
|
|
import concurrent.futures
|
2013-10-17 17:40:50 -03:00
|
|
|
import logging
|
2013-12-19 17:42:40 -04:00
|
|
|
import sys
|
2013-10-17 17:40:50 -03:00
|
|
|
import traceback
|
|
|
|
|
2016-10-28 13:52:37 -03:00
|
|
|
from . import base_futures
|
2013-10-17 17:40:50 -03:00
|
|
|
from . import events
|
|
|
|
|
|
|
|
|
2016-10-28 13:52:37 -03:00
|
|
|
CancelledError = base_futures.CancelledError
|
|
|
|
InvalidStateError = base_futures.InvalidStateError
|
|
|
|
TimeoutError = base_futures.TimeoutError
|
|
|
|
isfuture = base_futures.isfuture
|
2013-10-17 17:40:50 -03:00
|
|
|
|
2016-10-28 13:52:37 -03:00
|
|
|
|
|
|
|
_PENDING = base_futures._PENDING
|
|
|
|
_CANCELLED = base_futures._CANCELLED
|
|
|
|
_FINISHED = base_futures._FINISHED
|
2013-10-17 17:40:50 -03:00
|
|
|
|
|
|
|
|
2016-10-28 13:52:37 -03:00
|
|
|
STACK_DEBUG = logging.DEBUG - 1 # heavy-duty debugging
|
2013-10-17 17:40:50 -03:00
|
|
|
|
|
|
|
|
|
|
|
class Future:
|
|
|
|
"""This class is *almost* compatible with concurrent.futures.Future.
|
|
|
|
|
|
|
|
Differences:
|
|
|
|
|
2017-11-07 12:03:28 -04:00
|
|
|
- This class is not thread-safe.
|
|
|
|
|
2013-10-17 17:40:50 -03:00
|
|
|
- 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
|
2017-11-07 12:03:28 -04:00
|
|
|
via the event loop's call_soon().
|
2013-10-17 17:40:50 -03:00
|
|
|
|
|
|
|
- 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.
|
|
|
|
_state = _PENDING
|
|
|
|
_result = None
|
|
|
|
_exception = None
|
|
|
|
_loop = None
|
2014-12-04 18:00:13 -04:00
|
|
|
_source_traceback = None
|
2013-10-17 17:40:50 -03:00
|
|
|
|
2016-09-09 16:54:54 -03:00
|
|
|
# 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 `yield from Future()` (correct) vs.
|
|
|
|
# `yield Future()` (incorrect).
|
|
|
|
_asyncio_future_blocking = False
|
2013-10-17 17:40:50 -03:00
|
|
|
|
2017-11-27 19:35:33 -04:00
|
|
|
_log_traceback = False
|
2013-10-17 17:40:50 -03:00
|
|
|
|
|
|
|
def __init__(self, *, loop=None):
|
|
|
|
"""Initialize the future.
|
|
|
|
|
2016-02-10 01:44:01 -04:00
|
|
|
The optional event_loop argument allows explicitly setting the event
|
2013-10-17 17:40:50 -03:00
|
|
|
loop object used by the future. If it's not provided, the future uses
|
|
|
|
the default event loop.
|
|
|
|
"""
|
|
|
|
if loop is None:
|
|
|
|
self._loop = events.get_event_loop()
|
|
|
|
else:
|
|
|
|
self._loop = loop
|
|
|
|
self._callbacks = []
|
2014-06-27 08:52:20 -03:00
|
|
|
if self._loop.get_debug():
|
2017-11-07 12:23:29 -04:00
|
|
|
self._source_traceback = events.extract_stack(sys._getframe(1))
|
2013-10-17 17:40:50 -03:00
|
|
|
|
2016-10-28 13:52:37 -03:00
|
|
|
_repr_info = base_futures._future_repr_info
|
2014-07-29 07:58:23 -03:00
|
|
|
|
|
|
|
def __repr__(self):
|
2016-10-09 02:44:47 -03:00
|
|
|
return '<%s %s>' % (self.__class__.__name__, ' '.join(self._repr_info()))
|
2013-10-17 17:40:50 -03:00
|
|
|
|
2017-04-24 22:57:18 -03:00
|
|
|
def __del__(self):
|
|
|
|
if not self._log_traceback:
|
|
|
|
# set_exception() was not called, or result() or exception()
|
|
|
|
# has consumed the exception
|
|
|
|
return
|
|
|
|
exc = self._exception
|
|
|
|
context = {
|
|
|
|
'message': ('%s exception was never retrieved'
|
|
|
|
% self.__class__.__name__),
|
|
|
|
'exception': exc,
|
|
|
|
'future': self,
|
|
|
|
}
|
|
|
|
if self._source_traceback:
|
|
|
|
context['source_traceback'] = self._source_traceback
|
|
|
|
self._loop.call_exception_handler(context)
|
2013-12-19 17:42:40 -04:00
|
|
|
|
2013-10-17 17:40:50 -03:00
|
|
|
def cancel(self):
|
|
|
|
"""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.
|
|
|
|
"""
|
2017-06-11 10:49:18 -03:00
|
|
|
self._log_traceback = False
|
2013-10-17 17:40:50 -03:00
|
|
|
if self._state != _PENDING:
|
|
|
|
return False
|
|
|
|
self._state = _CANCELLED
|
2016-10-28 13:52:37 -03:00
|
|
|
self._schedule_callbacks()
|
2013-10-17 17:40:50 -03:00
|
|
|
return True
|
|
|
|
|
2016-10-28 13:52:37 -03:00
|
|
|
def _schedule_callbacks(self):
|
2013-10-17 17:40:50 -03:00
|
|
|
"""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.
|
|
|
|
"""
|
|
|
|
callbacks = self._callbacks[:]
|
|
|
|
if not callbacks:
|
|
|
|
return
|
|
|
|
|
|
|
|
self._callbacks[:] = []
|
|
|
|
for callback in callbacks:
|
|
|
|
self._loop.call_soon(callback, self)
|
|
|
|
|
|
|
|
def cancelled(self):
|
|
|
|
"""Return True if the future was cancelled."""
|
|
|
|
return self._state == _CANCELLED
|
|
|
|
|
|
|
|
# Don't implement running(); see http://bugs.python.org/issue18699
|
|
|
|
|
|
|
|
def done(self):
|
|
|
|
"""Return True if the future is done.
|
|
|
|
|
|
|
|
Done means either that a result / exception are available, or that the
|
|
|
|
future was cancelled.
|
|
|
|
"""
|
|
|
|
return self._state != _PENDING
|
|
|
|
|
|
|
|
def result(self):
|
|
|
|
"""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.
|
|
|
|
"""
|
|
|
|
if self._state == _CANCELLED:
|
|
|
|
raise CancelledError
|
|
|
|
if self._state != _FINISHED:
|
|
|
|
raise InvalidStateError('Result is not ready.')
|
2013-12-20 19:19:33 -04:00
|
|
|
self._log_traceback = False
|
2013-10-17 17:40:50 -03:00
|
|
|
if self._exception is not None:
|
|
|
|
raise self._exception
|
|
|
|
return self._result
|
|
|
|
|
|
|
|
def exception(self):
|
|
|
|
"""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.
|
|
|
|
"""
|
|
|
|
if self._state == _CANCELLED:
|
|
|
|
raise CancelledError
|
|
|
|
if self._state != _FINISHED:
|
|
|
|
raise InvalidStateError('Exception is not set.')
|
2013-12-20 19:19:33 -04:00
|
|
|
self._log_traceback = False
|
2013-10-17 17:40:50 -03:00
|
|
|
return self._exception
|
|
|
|
|
|
|
|
def add_done_callback(self, fn):
|
|
|
|
"""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.
|
|
|
|
"""
|
|
|
|
if self._state != _PENDING:
|
|
|
|
self._loop.call_soon(fn, self)
|
|
|
|
else:
|
|
|
|
self._callbacks.append(fn)
|
|
|
|
|
|
|
|
# New method not in PEP 3148.
|
|
|
|
|
|
|
|
def remove_done_callback(self, fn):
|
|
|
|
"""Remove all instances of a callback from the "call when done" list.
|
|
|
|
|
|
|
|
Returns the number of callbacks removed.
|
|
|
|
"""
|
|
|
|
filtered_callbacks = [f for f in self._callbacks if f != fn]
|
|
|
|
removed_count = len(self._callbacks) - len(filtered_callbacks)
|
|
|
|
if removed_count:
|
|
|
|
self._callbacks[:] = filtered_callbacks
|
|
|
|
return removed_count
|
|
|
|
|
|
|
|
# So-called internal methods (note: no set_running_or_notify_cancel()).
|
|
|
|
|
|
|
|
def set_result(self, result):
|
|
|
|
"""Mark the future done and set its result.
|
|
|
|
|
|
|
|
If the future is already done when this method is called, raises
|
|
|
|
InvalidStateError.
|
|
|
|
"""
|
|
|
|
if self._state != _PENDING:
|
|
|
|
raise InvalidStateError('{}: {!r}'.format(self._state, self))
|
|
|
|
self._result = result
|
|
|
|
self._state = _FINISHED
|
2016-10-28 13:52:37 -03:00
|
|
|
self._schedule_callbacks()
|
2013-10-17 17:40:50 -03:00
|
|
|
|
|
|
|
def set_exception(self, exception):
|
|
|
|
"""Mark the future done and set an exception.
|
|
|
|
|
|
|
|
If the future is already done when this method is called, raises
|
|
|
|
InvalidStateError.
|
|
|
|
"""
|
|
|
|
if self._state != _PENDING:
|
|
|
|
raise InvalidStateError('{}: {!r}'.format(self._state, self))
|
2014-01-30 20:01:54 -04:00
|
|
|
if isinstance(exception, type):
|
|
|
|
exception = exception()
|
2016-03-02 12:03:28 -04:00
|
|
|
if type(exception) is StopIteration:
|
|
|
|
raise TypeError("StopIteration interacts badly with generators "
|
|
|
|
"and cannot be raised into a Future")
|
2013-10-17 17:40:50 -03:00
|
|
|
self._exception = exception
|
|
|
|
self._state = _FINISHED
|
2016-10-28 13:52:37 -03:00
|
|
|
self._schedule_callbacks()
|
2017-04-24 22:57:18 -03:00
|
|
|
self._log_traceback = True
|
2013-10-17 17:40:50 -03:00
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
if not self.done():
|
2016-09-09 16:54:54 -03:00
|
|
|
self._asyncio_future_blocking = True
|
2013-10-17 17:40:50 -03:00
|
|
|
yield self # This tells Task to wait for completion.
|
|
|
|
assert self.done(), "yield from wasn't used with future"
|
|
|
|
return self.result() # May raise too.
|
|
|
|
|
2017-11-28 09:43:52 -04:00
|
|
|
__await__ = __iter__ # make compatible with 'await' expression
|
2015-05-11 23:27:25 -03:00
|
|
|
|
2013-10-17 17:40:50 -03:00
|
|
|
|
2016-10-23 23:34:35 -03:00
|
|
|
# Needed for testing purposes.
|
|
|
|
_PyFuture = Future
|
|
|
|
|
|
|
|
|
2015-11-17 13:19:41 -04:00
|
|
|
def _set_result_unless_cancelled(fut, result):
|
|
|
|
"""Helper setting the result only if the future was not cancelled."""
|
|
|
|
if fut.cancelled():
|
|
|
|
return
|
|
|
|
fut.set_result(result)
|
|
|
|
|
|
|
|
|
2015-10-03 12:31:42 -03:00
|
|
|
def _set_concurrent_future_state(concurrent, source):
|
|
|
|
"""Copy state from a future to a concurrent.futures.Future."""
|
|
|
|
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(exception)
|
|
|
|
else:
|
|
|
|
result = source.result()
|
|
|
|
concurrent.set_result(result)
|
|
|
|
|
|
|
|
|
2015-11-17 13:19:41 -04:00
|
|
|
def _copy_future_state(source, dest):
|
|
|
|
"""Internal helper to copy state from another Future.
|
|
|
|
|
|
|
|
The other Future may be a concurrent.futures.Future.
|
|
|
|
"""
|
|
|
|
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(exception)
|
|
|
|
else:
|
|
|
|
result = source.result()
|
|
|
|
dest.set_result(result)
|
|
|
|
|
|
|
|
|
2015-10-03 12:31:42 -03:00
|
|
|
def _chain_future(source, destination):
|
|
|
|
"""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.
|
|
|
|
"""
|
2016-09-09 18:26:31 -03:00
|
|
|
if not isfuture(source) and not isinstance(source,
|
|
|
|
concurrent.futures.Future):
|
2015-10-03 12:31:42 -03:00
|
|
|
raise TypeError('A future is required for source argument')
|
2016-09-09 18:26:31 -03:00
|
|
|
if not isfuture(destination) and not isinstance(destination,
|
|
|
|
concurrent.futures.Future):
|
2015-10-03 12:31:42 -03:00
|
|
|
raise TypeError('A future is required for destination argument')
|
2016-09-09 18:26:31 -03:00
|
|
|
source_loop = source._loop if isfuture(source) else None
|
|
|
|
dest_loop = destination._loop if isfuture(destination) else None
|
2015-10-03 12:31:42 -03:00
|
|
|
|
|
|
|
def _set_state(future, other):
|
2016-09-09 18:26:31 -03:00
|
|
|
if isfuture(future):
|
2015-11-17 13:19:41 -04:00
|
|
|
_copy_future_state(other, future)
|
2015-10-03 12:31:42 -03:00
|
|
|
else:
|
|
|
|
_set_concurrent_future_state(future, other)
|
2013-11-22 15:47:22 -04:00
|
|
|
|
2015-10-03 12:31:42 -03:00
|
|
|
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)
|
2013-11-22 15:47:22 -04:00
|
|
|
|
2015-10-03 12:31:42 -03:00
|
|
|
def _call_set_state(source):
|
|
|
|
if dest_loop is None or dest_loop is source_loop:
|
|
|
|
_set_state(destination, source)
|
|
|
|
else:
|
|
|
|
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):
|
|
|
|
"""Wrap concurrent.futures.Future object."""
|
2016-09-09 18:26:31 -03:00
|
|
|
if isfuture(future):
|
2015-10-03 12:31:42 -03:00
|
|
|
return future
|
|
|
|
assert isinstance(future, concurrent.futures.Future), \
|
|
|
|
'concurrent.futures.Future is expected, got {!r}'.format(future)
|
2016-05-16 16:38:39 -03:00
|
|
|
if loop is None:
|
|
|
|
loop = events.get_event_loop()
|
|
|
|
new_future = loop.create_future()
|
2015-10-03 12:31:42 -03:00
|
|
|
_chain_future(future, new_future)
|
2013-10-17 17:40:50 -03:00
|
|
|
return new_future
|
2016-10-17 23:48:14 -03:00
|
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
import _asyncio
|
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
else:
|
2016-10-23 23:34:35 -03:00
|
|
|
# _CFuture is needed for tests.
|
|
|
|
Future = _CFuture = _asyncio.Future
|