futures.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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. def __repr__(self):
  66. return base_futures._future_repr(self)
  67. def __del__(self):
  68. if not self.__log_traceback:
  69. # set_exception() was not called, or result() or exception()
  70. # has consumed the exception
  71. return
  72. exc = self._exception
  73. context = {
  74. 'message':
  75. f'{self.__class__.__name__} exception was never retrieved',
  76. 'exception': exc,
  77. 'future': self,
  78. }
  79. if self._source_traceback:
  80. context['source_traceback'] = self._source_traceback
  81. self._loop.call_exception_handler(context)
  82. __class_getitem__ = classmethod(GenericAlias)
  83. @property
  84. def _log_traceback(self):
  85. return self.__log_traceback
  86. @_log_traceback.setter
  87. def _log_traceback(self, val):
  88. if val:
  89. raise ValueError('_log_traceback can only be set to False')
  90. self.__log_traceback = False
  91. def get_loop(self):
  92. """Return the event loop the Future is bound to."""
  93. loop = self._loop
  94. if loop is None:
  95. raise RuntimeError("Future object is not initialized.")
  96. return loop
  97. def _make_cancelled_error(self):
  98. """Create the CancelledError to raise if the Future is cancelled.
  99. This should only be called once when handling a cancellation since
  100. it erases the saved context exception value.
  101. """
  102. if self._cancelled_exc is not None:
  103. exc = self._cancelled_exc
  104. self._cancelled_exc = None
  105. return exc
  106. if self._cancel_message is None:
  107. exc = exceptions.CancelledError()
  108. else:
  109. exc = exceptions.CancelledError(self._cancel_message)
  110. exc.__context__ = self._cancelled_exc
  111. # Remove the reference since we don't need this anymore.
  112. self._cancelled_exc = None
  113. return exc
  114. def cancel(self, msg=None):
  115. """Cancel the future and schedule callbacks.
  116. If the future is already done or cancelled, return False. Otherwise,
  117. change the future's state to cancelled, schedule the callbacks and
  118. return True.
  119. """
  120. self.__log_traceback = False
  121. if self._state != _PENDING:
  122. return False
  123. self._state = _CANCELLED
  124. self._cancel_message = msg
  125. self.__schedule_callbacks()
  126. return True
  127. def __schedule_callbacks(self):
  128. """Internal: Ask the event loop to call all callbacks.
  129. The callbacks are scheduled to be called as soon as possible. Also
  130. clears the callback list.
  131. """
  132. callbacks = self._callbacks[:]
  133. if not callbacks:
  134. return
  135. self._callbacks[:] = []
  136. for callback, ctx in callbacks:
  137. self._loop.call_soon(callback, self, context=ctx)
  138. def cancelled(self):
  139. """Return True if the future was cancelled."""
  140. return self._state == _CANCELLED
  141. # Don't implement running(); see http://bugs.python.org/issue18699
  142. def done(self):
  143. """Return True if the future is done.
  144. Done means either that a result / exception are available, or that the
  145. future was cancelled.
  146. """
  147. return self._state != _PENDING
  148. def result(self):
  149. """Return the result this future represents.
  150. If the future has been cancelled, raises CancelledError. If the
  151. future's result isn't yet available, raises InvalidStateError. If
  152. the future is done and has an exception set, this exception is raised.
  153. """
  154. if self._state == _CANCELLED:
  155. exc = self._make_cancelled_error()
  156. raise exc
  157. if self._state != _FINISHED:
  158. raise exceptions.InvalidStateError('Result is not ready.')
  159. self.__log_traceback = False
  160. if self._exception is not None:
  161. raise self._exception.with_traceback(self._exception_tb)
  162. return self._result
  163. def exception(self):
  164. """Return the exception that was set on this future.
  165. The exception (or None if no exception was set) is returned only if
  166. the future is done. If the future has been cancelled, raises
  167. CancelledError. If the future isn't done yet, raises
  168. InvalidStateError.
  169. """
  170. if self._state == _CANCELLED:
  171. exc = self._make_cancelled_error()
  172. raise exc
  173. if self._state != _FINISHED:
  174. raise exceptions.InvalidStateError('Exception is not set.')
  175. self.__log_traceback = False
  176. return self._exception
  177. def add_done_callback(self, fn, *, context=None):
  178. """Add a callback to be run when the future becomes done.
  179. The callback is called with a single argument - the future object. If
  180. the future is already done when this is called, the callback is
  181. scheduled with call_soon.
  182. """
  183. if self._state != _PENDING:
  184. self._loop.call_soon(fn, self, context=context)
  185. else:
  186. if context is None:
  187. context = contextvars.copy_context()
  188. self._callbacks.append((fn, context))
  189. # New method not in PEP 3148.
  190. def remove_done_callback(self, fn):
  191. """Remove all instances of a callback from the "call when done" list.
  192. Returns the number of callbacks removed.
  193. """
  194. filtered_callbacks = [(f, ctx)
  195. for (f, ctx) in self._callbacks
  196. if f != fn]
  197. removed_count = len(self._callbacks) - len(filtered_callbacks)
  198. if removed_count:
  199. self._callbacks[:] = filtered_callbacks
  200. return removed_count
  201. # So-called internal methods (note: no set_running_or_notify_cancel()).
  202. def set_result(self, result):
  203. """Mark the future done and set its result.
  204. If the future is already done when this method is called, raises
  205. InvalidStateError.
  206. """
  207. if self._state != _PENDING:
  208. raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
  209. self._result = result
  210. self._state = _FINISHED
  211. self.__schedule_callbacks()
  212. def set_exception(self, exception):
  213. """Mark the future done and set an exception.
  214. If the future is already done when this method is called, raises
  215. InvalidStateError.
  216. """
  217. if self._state != _PENDING:
  218. raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
  219. if isinstance(exception, type):
  220. exception = exception()
  221. if type(exception) is StopIteration:
  222. raise TypeError("StopIteration interacts badly with generators "
  223. "and cannot be raised into a Future")
  224. self._exception = exception
  225. self._exception_tb = exception.__traceback__
  226. self._state = _FINISHED
  227. self.__schedule_callbacks()
  228. self.__log_traceback = True
  229. def __await__(self):
  230. if not self.done():
  231. self._asyncio_future_blocking = True
  232. yield self # This tells Task to wait for completion.
  233. if not self.done():
  234. raise RuntimeError("await wasn't used with future")
  235. return self.result() # May raise too.
  236. __iter__ = __await__ # make compatible with 'yield from'.
  237. # Needed for testing purposes.
  238. _PyFuture = Future
  239. def _get_loop(fut):
  240. # Tries to call Future.get_loop() if it's available.
  241. # Otherwise fallbacks to using the old '_loop' property.
  242. try:
  243. get_loop = fut.get_loop
  244. except AttributeError:
  245. pass
  246. else:
  247. return get_loop()
  248. return fut._loop
  249. def _set_result_unless_cancelled(fut, result):
  250. """Helper setting the result only if the future was not cancelled."""
  251. if fut.cancelled():
  252. return
  253. fut.set_result(result)
  254. def _convert_future_exc(exc):
  255. exc_class = type(exc)
  256. if exc_class is concurrent.futures.CancelledError:
  257. return exceptions.CancelledError(*exc.args)
  258. elif exc_class is concurrent.futures.TimeoutError:
  259. return exceptions.TimeoutError(*exc.args)
  260. elif exc_class is concurrent.futures.InvalidStateError:
  261. return exceptions.InvalidStateError(*exc.args)
  262. else:
  263. return exc
  264. def _set_concurrent_future_state(concurrent, source):
  265. """Copy state from a future to a concurrent.futures.Future."""
  266. assert source.done()
  267. if source.cancelled():
  268. concurrent.cancel()
  269. if not concurrent.set_running_or_notify_cancel():
  270. return
  271. exception = source.exception()
  272. if exception is not None:
  273. concurrent.set_exception(_convert_future_exc(exception))
  274. else:
  275. result = source.result()
  276. concurrent.set_result(result)
  277. def _copy_future_state(source, dest):
  278. """Internal helper to copy state from another Future.
  279. The other Future may be a concurrent.futures.Future.
  280. """
  281. assert source.done()
  282. if dest.cancelled():
  283. return
  284. assert not dest.done()
  285. if source.cancelled():
  286. dest.cancel()
  287. else:
  288. exception = source.exception()
  289. if exception is not None:
  290. dest.set_exception(_convert_future_exc(exception))
  291. else:
  292. result = source.result()
  293. dest.set_result(result)
  294. def _chain_future(source, destination):
  295. """Chain two futures so that when one completes, so does the other.
  296. The result (or exception) of source will be copied to destination.
  297. If destination is cancelled, source gets cancelled too.
  298. Compatible with both asyncio.Future and concurrent.futures.Future.
  299. """
  300. if not isfuture(source) and not isinstance(source,
  301. concurrent.futures.Future):
  302. raise TypeError('A future is required for source argument')
  303. if not isfuture(destination) and not isinstance(destination,
  304. concurrent.futures.Future):
  305. raise TypeError('A future is required for destination argument')
  306. source_loop = _get_loop(source) if isfuture(source) else None
  307. dest_loop = _get_loop(destination) if isfuture(destination) else None
  308. def _set_state(future, other):
  309. if isfuture(future):
  310. _copy_future_state(other, future)
  311. else:
  312. _set_concurrent_future_state(future, other)
  313. def _call_check_cancel(destination):
  314. if destination.cancelled():
  315. if source_loop is None or source_loop is dest_loop:
  316. source.cancel()
  317. else:
  318. source_loop.call_soon_threadsafe(source.cancel)
  319. def _call_set_state(source):
  320. if (destination.cancelled() and
  321. dest_loop is not None and dest_loop.is_closed()):
  322. return
  323. if dest_loop is None or dest_loop is source_loop:
  324. _set_state(destination, source)
  325. else:
  326. if dest_loop.is_closed():
  327. return
  328. dest_loop.call_soon_threadsafe(_set_state, destination, source)
  329. destination.add_done_callback(_call_check_cancel)
  330. source.add_done_callback(_call_set_state)
  331. def wrap_future(future, *, loop=None):
  332. """Wrap concurrent.futures.Future object."""
  333. if isfuture(future):
  334. return future
  335. assert isinstance(future, concurrent.futures.Future), \
  336. f'concurrent.futures.Future is expected, got {future!r}'
  337. if loop is None:
  338. loop = events.get_event_loop()
  339. new_future = loop.create_future()
  340. _chain_future(future, new_future)
  341. return new_future
  342. try:
  343. import _asyncio
  344. except ImportError:
  345. pass
  346. else:
  347. # _CFuture is needed for tests.
  348. Future = _CFuture = _asyncio.Future