futures.py 13 KB

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