futures.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. """A Future class similar to the one in PEP 3148."""
  2. __all__ = (
  3. 'Future', 'wrap_future', 'isfuture',
  4. )
  5. import concurrent.futures
  6. import contextvars
  7. import logging
  8. import sys
  9. from types import GenericAlias
  10. from . import base_futures
  11. from . import events
  12. from . import exceptions
  13. from . import format_helpers
  14. isfuture = base_futures.isfuture
  15. _PENDING = base_futures._PENDING
  16. _CANCELLED = base_futures._CANCELLED
  17. _FINISHED = base_futures._FINISHED
  18. STACK_DEBUG = logging.DEBUG - 1 # heavy-duty debugging
  19. class Future:
  20. """This class is *almost* compatible with concurrent.futures.Future.
  21. Differences:
  22. - This class is not thread-safe.
  23. - result() and exception() do not take a timeout argument and
  24. raise an exception when the future isn't done yet.
  25. - Callbacks registered with add_done_callback() are always called
  26. via the event loop's call_soon().
  27. - This class is not compatible with the wait() and as_completed()
  28. methods in the concurrent.futures package.
  29. (In Python 3.4 or later we may be able to unify the implementations.)
  30. """
  31. # Class variables serving as defaults for instance variables.
  32. _state = _PENDING
  33. _result = None
  34. _exception = None
  35. _loop = None
  36. _source_traceback = None
  37. _cancel_message = None
  38. # A saved CancelledError for later chaining as an exception context.
  39. _cancelled_exc = None
  40. # This field is used for a dual purpose:
  41. # - Its presence is a marker to declare that a class implements
  42. # the Future protocol (i.e. is intended to be duck-type compatible).
  43. # The value must also be not-None, to enable a subclass to declare
  44. # that it is not compatible by setting this to None.
  45. # - It is set by __iter__() below so that Task._step() can tell
  46. # the difference between
  47. # `await Future()` or`yield from Future()` (correct) vs.
  48. # `yield Future()` (incorrect).
  49. _asyncio_future_blocking = False
  50. __log_traceback = False
  51. def __init__(self, *, loop=None):
  52. """Initialize the future.
  53. The optional event_loop argument allows explicitly setting the event
  54. loop object used by the future. If it's not provided, the future uses
  55. the default event loop.
  56. """
  57. if loop is None:
  58. self._loop = events.get_event_loop()
  59. else:
  60. self._loop = loop
  61. self._callbacks = []
  62. if self._loop.get_debug():
  63. self._source_traceback = format_helpers.extract_stack(
  64. sys._getframe(1))
  65. _repr_info = base_futures._future_repr_info
  66. def __repr__(self):
  67. return '<{} {}>'.format(self.__class__.__name__,
  68. ' '.join(self._repr_info()))
  69. def __del__(self):
  70. if not self.__log_traceback:
  71. # set_exception() was not called, or result() or exception()
  72. # has consumed the exception
  73. return
  74. exc = self._exception
  75. context = {
  76. 'message':
  77. f'{self.__class__.__name__} exception was never retrieved',
  78. 'exception': exc,
  79. 'future': self,
  80. }
  81. if self._source_traceback:
  82. context['source_traceback'] = self._source_traceback
  83. self._loop.call_exception_handler(context)
  84. __class_getitem__ = classmethod(GenericAlias)
  85. @property
  86. def _log_traceback(self):
  87. return self.__log_traceback
  88. @_log_traceback.setter
  89. def _log_traceback(self, val):
  90. if bool(val):
  91. raise ValueError('_log_traceback can only be set to False')
  92. self.__log_traceback = False
  93. def get_loop(self):
  94. """Return the event loop the Future is bound to."""
  95. loop = self._loop
  96. if loop is None:
  97. raise RuntimeError("Future object is not initialized.")
  98. return loop
  99. def _make_cancelled_error(self):
  100. """Create the CancelledError to raise if the Future is cancelled.
  101. This should only be called once when handling a cancellation since
  102. it erases the saved context exception value.
  103. """
  104. if self._cancel_message is None:
  105. exc = exceptions.CancelledError()
  106. else:
  107. exc = exceptions.CancelledError(self._cancel_message)
  108. exc.__context__ = self._cancelled_exc
  109. # Remove the reference since we don't need this anymore.
  110. self._cancelled_exc = None
  111. return exc
  112. def cancel(self, msg=None):
  113. """Cancel the future and schedule callbacks.
  114. If the future is already done or cancelled, return False. Otherwise,
  115. change the future's state to cancelled, schedule the callbacks and
  116. return True.
  117. """
  118. self.__log_traceback = False
  119. if self._state != _PENDING:
  120. return False
  121. self._state = _CANCELLED
  122. self._cancel_message = msg
  123. self.__schedule_callbacks()
  124. return True
  125. def __schedule_callbacks(self):
  126. """Internal: Ask the event loop to call all callbacks.
  127. The callbacks are scheduled to be called as soon as possible. Also
  128. clears the callback list.
  129. """
  130. callbacks = self._callbacks[:]
  131. if not callbacks:
  132. return
  133. self._callbacks[:] = []
  134. for callback, ctx in callbacks:
  135. self._loop.call_soon(callback, self, context=ctx)
  136. def cancelled(self):
  137. """Return True if the future was cancelled."""
  138. return self._state == _CANCELLED
  139. # Don't implement running(); see http://bugs.python.org/issue18699
  140. def done(self):
  141. """Return True if the future is done.
  142. Done means either that a result / exception are available, or that the
  143. future was cancelled.
  144. """
  145. return self._state != _PENDING
  146. def result(self):
  147. """Return the result this future represents.
  148. If the future has been cancelled, raises CancelledError. If the
  149. future's result isn't yet available, raises InvalidStateError. If
  150. the future is done and has an exception set, this exception is raised.
  151. """
  152. if self._state == _CANCELLED:
  153. exc = self._make_cancelled_error()
  154. raise exc
  155. if self._state != _FINISHED:
  156. raise exceptions.InvalidStateError('Result is not ready.')
  157. self.__log_traceback = False
  158. if self._exception is not None:
  159. raise self._exception
  160. return self._result
  161. def exception(self):
  162. """Return the exception that was set on this future.
  163. The exception (or None if no exception was set) is returned only if
  164. the future is done. If the future has been cancelled, raises
  165. CancelledError. If the future isn't done yet, raises
  166. InvalidStateError.
  167. """
  168. if self._state == _CANCELLED:
  169. exc = self._make_cancelled_error()
  170. raise exc
  171. if self._state != _FINISHED:
  172. raise exceptions.InvalidStateError('Exception is not set.')
  173. self.__log_traceback = False
  174. return self._exception
  175. def add_done_callback(self, fn, *, context=None):
  176. """Add a callback to be run when the future becomes done.
  177. The callback is called with a single argument - the future object. If
  178. the future is already done when this is called, the callback is
  179. scheduled with call_soon.
  180. """
  181. if self._state != _PENDING:
  182. self._loop.call_soon(fn, self, context=context)
  183. else:
  184. if context is None:
  185. context = contextvars.copy_context()
  186. self._callbacks.append((fn, context))
  187. # New method not in PEP 3148.
  188. def remove_done_callback(self, fn):
  189. """Remove all instances of a callback from the "call when done" list.
  190. Returns the number of callbacks removed.
  191. """
  192. filtered_callbacks = [(f, ctx)
  193. for (f, ctx) in self._callbacks
  194. if f != fn]
  195. removed_count = len(self._callbacks) - len(filtered_callbacks)
  196. if removed_count:
  197. self._callbacks[:] = filtered_callbacks
  198. return removed_count
  199. # So-called internal methods (note: no set_running_or_notify_cancel()).
  200. def set_result(self, result):
  201. """Mark the future done and set its result.
  202. If the future is already done when this method is called, raises
  203. InvalidStateError.
  204. """
  205. if self._state != _PENDING:
  206. raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
  207. self._result = result
  208. self._state = _FINISHED
  209. self.__schedule_callbacks()
  210. def set_exception(self, exception):
  211. """Mark the future done and set an exception.
  212. If the future is already done when this method is called, raises
  213. InvalidStateError.
  214. """
  215. if self._state != _PENDING:
  216. raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
  217. if isinstance(exception, type):
  218. exception = exception()
  219. if type(exception) is StopIteration:
  220. raise TypeError("StopIteration interacts badly with generators "
  221. "and cannot be raised into a Future")
  222. self._exception = exception
  223. self._state = _FINISHED
  224. self.__schedule_callbacks()
  225. self.__log_traceback = True
  226. def __await__(self):
  227. if not self.done():
  228. self._asyncio_future_blocking = True
  229. yield self # This tells Task to wait for completion.
  230. if not self.done():
  231. raise RuntimeError("await wasn't used with future")
  232. return self.result() # May raise too.
  233. __iter__ = __await__ # make compatible with 'yield from'.
  234. # Needed for testing purposes.
  235. _PyFuture = Future
  236. def _get_loop(fut):
  237. # Tries to call Future.get_loop() if it's available.
  238. # Otherwise fallbacks to using the old '_loop' property.
  239. try:
  240. get_loop = fut.get_loop
  241. except AttributeError:
  242. pass
  243. else:
  244. return get_loop()
  245. return fut._loop
  246. def _set_result_unless_cancelled(fut, result):
  247. """Helper setting the result only if the future was not cancelled."""
  248. if fut.cancelled():
  249. return
  250. fut.set_result(result)
  251. def _convert_future_exc(exc):
  252. exc_class = type(exc)
  253. if exc_class is concurrent.futures.CancelledError:
  254. return exceptions.CancelledError(*exc.args)
  255. elif exc_class is concurrent.futures.TimeoutError:
  256. return exceptions.TimeoutError(*exc.args)
  257. elif exc_class is concurrent.futures.InvalidStateError:
  258. return exceptions.InvalidStateError(*exc.args)
  259. else:
  260. return exc
  261. def _set_concurrent_future_state(concurrent, source):
  262. """Copy state from a future to a concurrent.futures.Future."""
  263. assert source.done()
  264. if source.cancelled():
  265. concurrent.cancel()
  266. if not concurrent.set_running_or_notify_cancel():
  267. return
  268. exception = source.exception()
  269. if exception is not None:
  270. concurrent.set_exception(_convert_future_exc(exception))
  271. else:
  272. result = source.result()
  273. concurrent.set_result(result)
  274. def _copy_future_state(source, dest):
  275. """Internal helper to copy state from another Future.
  276. The other Future may be a concurrent.futures.Future.
  277. """
  278. assert source.done()
  279. if dest.cancelled():
  280. return
  281. assert not dest.done()
  282. if source.cancelled():
  283. dest.cancel()
  284. else:
  285. exception = source.exception()
  286. if exception is not None:
  287. dest.set_exception(_convert_future_exc(exception))
  288. else:
  289. result = source.result()
  290. dest.set_result(result)
  291. def _chain_future(source, destination):
  292. """Chain two futures so that when one completes, so does the other.
  293. The result (or exception) of source will be copied to destination.
  294. If destination is cancelled, source gets cancelled too.
  295. Compatible with both asyncio.Future and concurrent.futures.Future.
  296. """
  297. if not isfuture(source) and not isinstance(source,
  298. concurrent.futures.Future):
  299. raise TypeError('A future is required for source argument')
  300. if not isfuture(destination) and not isinstance(destination,
  301. concurrent.futures.Future):
  302. raise TypeError('A future is required for destination argument')
  303. source_loop = _get_loop(source) if isfuture(source) else None
  304. dest_loop = _get_loop(destination) if isfuture(destination) else None
  305. def _set_state(future, other):
  306. if isfuture(future):
  307. _copy_future_state(other, future)
  308. else:
  309. _set_concurrent_future_state(future, other)
  310. def _call_check_cancel(destination):
  311. if destination.cancelled():
  312. if source_loop is None or source_loop is dest_loop:
  313. source.cancel()
  314. else:
  315. source_loop.call_soon_threadsafe(source.cancel)
  316. def _call_set_state(source):
  317. if (destination.cancelled() and
  318. dest_loop is not None and dest_loop.is_closed()):
  319. return
  320. if dest_loop is None or dest_loop is source_loop:
  321. _set_state(destination, source)
  322. else:
  323. dest_loop.call_soon_threadsafe(_set_state, destination, source)
  324. destination.add_done_callback(_call_check_cancel)
  325. source.add_done_callback(_call_set_state)
  326. def wrap_future(future, *, loop=None):
  327. """Wrap concurrent.futures.Future object."""
  328. if isfuture(future):
  329. return future
  330. assert isinstance(future, concurrent.futures.Future), \
  331. f'concurrent.futures.Future is expected, got {future!r}'
  332. if loop is None:
  333. loop = events.get_event_loop()
  334. new_future = loop.create_future()
  335. _chain_future(future, new_future)
  336. return new_future
  337. try:
  338. import _asyncio
  339. except ImportError:
  340. pass
  341. else:
  342. # _CFuture is needed for tests.
  343. Future = _CFuture = _asyncio.Future