tasks.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  1. """Support for tasks, coroutines and the scheduler."""
  2. __all__ = (
  3. 'Task', 'create_task',
  4. 'FIRST_COMPLETED', 'FIRST_EXCEPTION', 'ALL_COMPLETED',
  5. 'wait', 'wait_for', 'as_completed', 'sleep',
  6. 'gather', 'shield', 'ensure_future', 'run_coroutine_threadsafe',
  7. 'current_task', 'all_tasks',
  8. '_register_task', '_unregister_task', '_enter_task', '_leave_task',
  9. )
  10. import concurrent.futures
  11. import contextvars
  12. import functools
  13. import inspect
  14. import itertools
  15. import types
  16. import warnings
  17. import weakref
  18. from types import GenericAlias
  19. from . import base_tasks
  20. from . import coroutines
  21. from . import events
  22. from . import exceptions
  23. from . import futures
  24. from .coroutines import _is_coroutine
  25. # Helper to generate new task names
  26. # This uses itertools.count() instead of a "+= 1" operation because the latter
  27. # is not thread safe. See bpo-11866 for a longer explanation.
  28. _task_name_counter = itertools.count(1).__next__
  29. def current_task(loop=None):
  30. """Return a currently executed task."""
  31. if loop is None:
  32. loop = events.get_running_loop()
  33. return _current_tasks.get(loop)
  34. def all_tasks(loop=None):
  35. """Return a set of all tasks for the loop."""
  36. if loop is None:
  37. loop = events.get_running_loop()
  38. # Looping over a WeakSet (_all_tasks) isn't safe as it can be updated from another
  39. # thread while we do so. Therefore we cast it to list prior to filtering. The list
  40. # cast itself requires iteration, so we repeat it several times ignoring
  41. # RuntimeErrors (which are not very likely to occur). See issues 34970 and 36607 for
  42. # details.
  43. i = 0
  44. while True:
  45. try:
  46. tasks = list(_all_tasks)
  47. except RuntimeError:
  48. i += 1
  49. if i >= 1000:
  50. raise
  51. else:
  52. break
  53. return {t for t in tasks
  54. if futures._get_loop(t) is loop and not t.done()}
  55. def _all_tasks_compat(loop=None):
  56. # Different from "all_task()" by returning *all* Tasks, including
  57. # the completed ones. Used to implement deprecated "Tasks.all_task()"
  58. # method.
  59. if loop is None:
  60. loop = events.get_event_loop()
  61. # Looping over a WeakSet (_all_tasks) isn't safe as it can be updated from another
  62. # thread while we do so. Therefore we cast it to list prior to filtering. The list
  63. # cast itself requires iteration, so we repeat it several times ignoring
  64. # RuntimeErrors (which are not very likely to occur). See issues 34970 and 36607 for
  65. # details.
  66. i = 0
  67. while True:
  68. try:
  69. tasks = list(_all_tasks)
  70. except RuntimeError:
  71. i += 1
  72. if i >= 1000:
  73. raise
  74. else:
  75. break
  76. return {t for t in tasks if futures._get_loop(t) is loop}
  77. def _set_task_name(task, name):
  78. if name is not None:
  79. try:
  80. set_name = task.set_name
  81. except AttributeError:
  82. pass
  83. else:
  84. set_name(name)
  85. class Task(futures._PyFuture): # Inherit Python Task implementation
  86. # from a Python Future implementation.
  87. """A coroutine wrapped in a Future."""
  88. # An important invariant maintained while a Task not done:
  89. #
  90. # - Either _fut_waiter is None, and _step() is scheduled;
  91. # - or _fut_waiter is some Future, and _step() is *not* scheduled.
  92. #
  93. # The only transition from the latter to the former is through
  94. # _wakeup(). When _fut_waiter is not None, one of its callbacks
  95. # must be _wakeup().
  96. # If False, don't log a message if the task is destroyed whereas its
  97. # status is still pending
  98. _log_destroy_pending = True
  99. def __init__(self, coro, *, loop=None, name=None):
  100. super().__init__(loop=loop)
  101. if self._source_traceback:
  102. del self._source_traceback[-1]
  103. if not coroutines.iscoroutine(coro):
  104. # raise after Future.__init__(), attrs are required for __del__
  105. # prevent logging for pending task in __del__
  106. self._log_destroy_pending = False
  107. raise TypeError(f"a coroutine was expected, got {coro!r}")
  108. if name is None:
  109. self._name = f'Task-{_task_name_counter()}'
  110. else:
  111. self._name = str(name)
  112. self._must_cancel = False
  113. self._fut_waiter = None
  114. self._coro = coro
  115. self._context = contextvars.copy_context()
  116. self._loop.call_soon(self.__step, context=self._context)
  117. _register_task(self)
  118. def __del__(self):
  119. if self._state == futures._PENDING and self._log_destroy_pending:
  120. context = {
  121. 'task': self,
  122. 'message': 'Task was destroyed but it is pending!',
  123. }
  124. if self._source_traceback:
  125. context['source_traceback'] = self._source_traceback
  126. self._loop.call_exception_handler(context)
  127. super().__del__()
  128. __class_getitem__ = classmethod(GenericAlias)
  129. def _repr_info(self):
  130. return base_tasks._task_repr_info(self)
  131. def get_coro(self):
  132. return self._coro
  133. def get_name(self):
  134. return self._name
  135. def set_name(self, value):
  136. self._name = str(value)
  137. def set_result(self, result):
  138. raise RuntimeError('Task does not support set_result operation')
  139. def set_exception(self, exception):
  140. raise RuntimeError('Task does not support set_exception operation')
  141. def get_stack(self, *, limit=None):
  142. """Return the list of stack frames for this task's coroutine.
  143. If the coroutine is not done, this returns the stack where it is
  144. suspended. If the coroutine has completed successfully or was
  145. cancelled, this returns an empty list. If the coroutine was
  146. terminated by an exception, this returns the list of traceback
  147. frames.
  148. The frames are always ordered from oldest to newest.
  149. The optional limit gives the maximum number of frames to
  150. return; by default all available frames are returned. Its
  151. meaning differs depending on whether a stack or a traceback is
  152. returned: the newest frames of a stack are returned, but the
  153. oldest frames of a traceback are returned. (This matches the
  154. behavior of the traceback module.)
  155. For reasons beyond our control, only one stack frame is
  156. returned for a suspended coroutine.
  157. """
  158. return base_tasks._task_get_stack(self, limit)
  159. def print_stack(self, *, limit=None, file=None):
  160. """Print the stack or traceback for this task's coroutine.
  161. This produces output similar to that of the traceback module,
  162. for the frames retrieved by get_stack(). The limit argument
  163. is passed to get_stack(). The file argument is an I/O stream
  164. to which the output is written; by default output is written
  165. to sys.stderr.
  166. """
  167. return base_tasks._task_print_stack(self, limit, file)
  168. def cancel(self, msg=None):
  169. """Request that this task cancel itself.
  170. This arranges for a CancelledError to be thrown into the
  171. wrapped coroutine on the next cycle through the event loop.
  172. The coroutine then has a chance to clean up or even deny
  173. the request using try/except/finally.
  174. Unlike Future.cancel, this does not guarantee that the
  175. task will be cancelled: the exception might be caught and
  176. acted upon, delaying cancellation of the task or preventing
  177. cancellation completely. The task may also return a value or
  178. raise a different exception.
  179. Immediately after this method is called, Task.cancelled() will
  180. not return True (unless the task was already cancelled). A
  181. task will be marked as cancelled when the wrapped coroutine
  182. terminates with a CancelledError exception (even if cancel()
  183. was not called).
  184. """
  185. self._log_traceback = False
  186. if self.done():
  187. return False
  188. if self._fut_waiter is not None:
  189. if self._fut_waiter.cancel(msg=msg):
  190. # Leave self._fut_waiter; it may be a Task that
  191. # catches and ignores the cancellation so we may have
  192. # to cancel it again later.
  193. return True
  194. # It must be the case that self.__step is already scheduled.
  195. self._must_cancel = True
  196. self._cancel_message = msg
  197. return True
  198. def __step(self, exc=None):
  199. if self.done():
  200. raise exceptions.InvalidStateError(
  201. f'_step(): already done: {self!r}, {exc!r}')
  202. if self._must_cancel:
  203. if not isinstance(exc, exceptions.CancelledError):
  204. exc = self._make_cancelled_error()
  205. self._must_cancel = False
  206. coro = self._coro
  207. self._fut_waiter = None
  208. _enter_task(self._loop, self)
  209. # Call either coro.throw(exc) or coro.send(None).
  210. try:
  211. if exc is None:
  212. # We use the `send` method directly, because coroutines
  213. # don't have `__iter__` and `__next__` methods.
  214. result = coro.send(None)
  215. else:
  216. result = coro.throw(exc)
  217. except StopIteration as exc:
  218. if self._must_cancel:
  219. # Task is cancelled right before coro stops.
  220. self._must_cancel = False
  221. super().cancel(msg=self._cancel_message)
  222. else:
  223. super().set_result(exc.value)
  224. except exceptions.CancelledError as exc:
  225. # Save the original exception so we can chain it later.
  226. self._cancelled_exc = exc
  227. super().cancel() # I.e., Future.cancel(self).
  228. except (KeyboardInterrupt, SystemExit) as exc:
  229. super().set_exception(exc)
  230. raise
  231. except BaseException as exc:
  232. super().set_exception(exc)
  233. else:
  234. blocking = getattr(result, '_asyncio_future_blocking', None)
  235. if blocking is not None:
  236. # Yielded Future must come from Future.__iter__().
  237. if futures._get_loop(result) is not self._loop:
  238. new_exc = RuntimeError(
  239. f'Task {self!r} got Future '
  240. f'{result!r} attached to a different loop')
  241. self._loop.call_soon(
  242. self.__step, new_exc, context=self._context)
  243. elif blocking:
  244. if result is self:
  245. new_exc = RuntimeError(
  246. f'Task cannot await on itself: {self!r}')
  247. self._loop.call_soon(
  248. self.__step, new_exc, context=self._context)
  249. else:
  250. result._asyncio_future_blocking = False
  251. result.add_done_callback(
  252. self.__wakeup, context=self._context)
  253. self._fut_waiter = result
  254. if self._must_cancel:
  255. if self._fut_waiter.cancel(
  256. msg=self._cancel_message):
  257. self._must_cancel = False
  258. else:
  259. new_exc = RuntimeError(
  260. f'yield was used instead of yield from '
  261. f'in task {self!r} with {result!r}')
  262. self._loop.call_soon(
  263. self.__step, new_exc, context=self._context)
  264. elif result is None:
  265. # Bare yield relinquishes control for one event loop iteration.
  266. self._loop.call_soon(self.__step, context=self._context)
  267. elif inspect.isgenerator(result):
  268. # Yielding a generator is just wrong.
  269. new_exc = RuntimeError(
  270. f'yield was used instead of yield from for '
  271. f'generator in task {self!r} with {result!r}')
  272. self._loop.call_soon(
  273. self.__step, new_exc, context=self._context)
  274. else:
  275. # Yielding something else is an error.
  276. new_exc = RuntimeError(f'Task got bad yield: {result!r}')
  277. self._loop.call_soon(
  278. self.__step, new_exc, context=self._context)
  279. finally:
  280. _leave_task(self._loop, self)
  281. self = None # Needed to break cycles when an exception occurs.
  282. def __wakeup(self, future):
  283. try:
  284. future.result()
  285. except BaseException as exc:
  286. # This may also be a cancellation.
  287. self.__step(exc)
  288. else:
  289. # Don't pass the value of `future.result()` explicitly,
  290. # as `Future.__iter__` and `Future.__await__` don't need it.
  291. # If we call `_step(value, None)` instead of `_step()`,
  292. # Python eval loop would use `.send(value)` method call,
  293. # instead of `__next__()`, which is slower for futures
  294. # that return non-generator iterators from their `__iter__`.
  295. self.__step()
  296. self = None # Needed to break cycles when an exception occurs.
  297. _PyTask = Task
  298. try:
  299. import _asyncio
  300. except ImportError:
  301. pass
  302. else:
  303. # _CTask is needed for tests.
  304. Task = _CTask = _asyncio.Task
  305. def create_task(coro, *, name=None):
  306. """Schedule the execution of a coroutine object in a spawn task.
  307. Return a Task object.
  308. """
  309. loop = events.get_running_loop()
  310. task = loop.create_task(coro)
  311. _set_task_name(task, name)
  312. return task
  313. # wait() and as_completed() similar to those in PEP 3148.
  314. FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED
  315. FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION
  316. ALL_COMPLETED = concurrent.futures.ALL_COMPLETED
  317. async def wait(fs, *, loop=None, timeout=None, return_when=ALL_COMPLETED):
  318. """Wait for the Futures and coroutines given by fs to complete.
  319. The fs iterable must not be empty.
  320. Coroutines will be wrapped in Tasks.
  321. Returns two sets of Future: (done, pending).
  322. Usage:
  323. done, pending = await asyncio.wait(fs)
  324. Note: This does not raise TimeoutError! Futures that aren't done
  325. when the timeout occurs are returned in the second set.
  326. """
  327. if futures.isfuture(fs) or coroutines.iscoroutine(fs):
  328. raise TypeError(f"expect a list of futures, not {type(fs).__name__}")
  329. if not fs:
  330. raise ValueError('Set of coroutines/Futures is empty.')
  331. if return_when not in (FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED):
  332. raise ValueError(f'Invalid return_when value: {return_when}')
  333. if loop is None:
  334. loop = events.get_running_loop()
  335. else:
  336. warnings.warn("The loop argument is deprecated since Python 3.8, "
  337. "and scheduled for removal in Python 3.10.",
  338. DeprecationWarning, stacklevel=2)
  339. fs = set(fs)
  340. if any(coroutines.iscoroutine(f) for f in fs):
  341. warnings.warn("The explicit passing of coroutine objects to "
  342. "asyncio.wait() is deprecated since Python 3.8, and "
  343. "scheduled for removal in Python 3.11.",
  344. DeprecationWarning, stacklevel=2)
  345. fs = {ensure_future(f, loop=loop) for f in fs}
  346. return await _wait(fs, timeout, return_when, loop)
  347. def _release_waiter(waiter, *args):
  348. if not waiter.done():
  349. waiter.set_result(None)
  350. async def wait_for(fut, timeout, *, loop=None):
  351. """Wait for the single Future or coroutine to complete, with timeout.
  352. Coroutine will be wrapped in Task.
  353. Returns result of the Future or coroutine. When a timeout occurs,
  354. it cancels the task and raises TimeoutError. To avoid the task
  355. cancellation, wrap it in shield().
  356. If the wait is cancelled, the task is also cancelled.
  357. This function is a coroutine.
  358. """
  359. if loop is None:
  360. loop = events.get_running_loop()
  361. else:
  362. warnings.warn("The loop argument is deprecated since Python 3.8, "
  363. "and scheduled for removal in Python 3.10.",
  364. DeprecationWarning, stacklevel=2)
  365. if timeout is None:
  366. return await fut
  367. if timeout <= 0:
  368. fut = ensure_future(fut, loop=loop)
  369. if fut.done():
  370. return fut.result()
  371. await _cancel_and_wait(fut, loop=loop)
  372. try:
  373. return fut.result()
  374. except exceptions.CancelledError as exc:
  375. raise exceptions.TimeoutError() from exc
  376. waiter = loop.create_future()
  377. timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
  378. cb = functools.partial(_release_waiter, waiter)
  379. fut = ensure_future(fut, loop=loop)
  380. fut.add_done_callback(cb)
  381. try:
  382. # wait until the future completes or the timeout
  383. try:
  384. await waiter
  385. except exceptions.CancelledError:
  386. if fut.done():
  387. return fut.result()
  388. else:
  389. fut.remove_done_callback(cb)
  390. # We must ensure that the task is not running
  391. # after wait_for() returns.
  392. # See https://bugs.python.org/issue32751
  393. await _cancel_and_wait(fut, loop=loop)
  394. raise
  395. if fut.done():
  396. return fut.result()
  397. else:
  398. fut.remove_done_callback(cb)
  399. # We must ensure that the task is not running
  400. # after wait_for() returns.
  401. # See https://bugs.python.org/issue32751
  402. await _cancel_and_wait(fut, loop=loop)
  403. # In case task cancellation failed with some
  404. # exception, we should re-raise it
  405. # See https://bugs.python.org/issue40607
  406. try:
  407. return fut.result()
  408. except exceptions.CancelledError as exc:
  409. raise exceptions.TimeoutError() from exc
  410. finally:
  411. timeout_handle.cancel()
  412. async def _wait(fs, timeout, return_when, loop):
  413. """Internal helper for wait().
  414. The fs argument must be a collection of Futures.
  415. """
  416. assert fs, 'Set of Futures is empty.'
  417. waiter = loop.create_future()
  418. timeout_handle = None
  419. if timeout is not None:
  420. timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
  421. counter = len(fs)
  422. def _on_completion(f):
  423. nonlocal counter
  424. counter -= 1
  425. if (counter <= 0 or
  426. return_when == FIRST_COMPLETED or
  427. return_when == FIRST_EXCEPTION and (not f.cancelled() and
  428. f.exception() is not None)):
  429. if timeout_handle is not None:
  430. timeout_handle.cancel()
  431. if not waiter.done():
  432. waiter.set_result(None)
  433. for f in fs:
  434. f.add_done_callback(_on_completion)
  435. try:
  436. await waiter
  437. finally:
  438. if timeout_handle is not None:
  439. timeout_handle.cancel()
  440. for f in fs:
  441. f.remove_done_callback(_on_completion)
  442. done, pending = set(), set()
  443. for f in fs:
  444. if f.done():
  445. done.add(f)
  446. else:
  447. pending.add(f)
  448. return done, pending
  449. async def _cancel_and_wait(fut, loop):
  450. """Cancel the *fut* future or task and wait until it completes."""
  451. waiter = loop.create_future()
  452. cb = functools.partial(_release_waiter, waiter)
  453. fut.add_done_callback(cb)
  454. try:
  455. fut.cancel()
  456. # We cannot wait on *fut* directly to make
  457. # sure _cancel_and_wait itself is reliably cancellable.
  458. await waiter
  459. finally:
  460. fut.remove_done_callback(cb)
  461. # This is *not* a @coroutine! It is just an iterator (yielding Futures).
  462. def as_completed(fs, *, loop=None, timeout=None):
  463. """Return an iterator whose values are coroutines.
  464. When waiting for the yielded coroutines you'll get the results (or
  465. exceptions!) of the original Futures (or coroutines), in the order
  466. in which and as soon as they complete.
  467. This differs from PEP 3148; the proper way to use this is:
  468. for f in as_completed(fs):
  469. result = await f # The 'await' may raise.
  470. # Use result.
  471. If a timeout is specified, the 'await' will raise
  472. TimeoutError when the timeout occurs before all Futures are done.
  473. Note: The futures 'f' are not necessarily members of fs.
  474. """
  475. if futures.isfuture(fs) or coroutines.iscoroutine(fs):
  476. raise TypeError(f"expect an iterable of futures, not {type(fs).__name__}")
  477. if loop is not None:
  478. warnings.warn("The loop argument is deprecated since Python 3.8, "
  479. "and scheduled for removal in Python 3.10.",
  480. DeprecationWarning, stacklevel=2)
  481. from .queues import Queue # Import here to avoid circular import problem.
  482. done = Queue(loop=loop)
  483. if loop is None:
  484. loop = events.get_event_loop()
  485. todo = {ensure_future(f, loop=loop) for f in set(fs)}
  486. timeout_handle = None
  487. def _on_timeout():
  488. for f in todo:
  489. f.remove_done_callback(_on_completion)
  490. done.put_nowait(None) # Queue a dummy value for _wait_for_one().
  491. todo.clear() # Can't do todo.remove(f) in the loop.
  492. def _on_completion(f):
  493. if not todo:
  494. return # _on_timeout() was here first.
  495. todo.remove(f)
  496. done.put_nowait(f)
  497. if not todo and timeout_handle is not None:
  498. timeout_handle.cancel()
  499. async def _wait_for_one():
  500. f = await done.get()
  501. if f is None:
  502. # Dummy value from _on_timeout().
  503. raise exceptions.TimeoutError
  504. return f.result() # May raise f.exception().
  505. for f in todo:
  506. f.add_done_callback(_on_completion)
  507. if todo and timeout is not None:
  508. timeout_handle = loop.call_later(timeout, _on_timeout)
  509. for _ in range(len(todo)):
  510. yield _wait_for_one()
  511. @types.coroutine
  512. def __sleep0():
  513. """Skip one event loop run cycle.
  514. This is a private helper for 'asyncio.sleep()', used
  515. when the 'delay' is set to 0. It uses a bare 'yield'
  516. expression (which Task.__step knows how to handle)
  517. instead of creating a Future object.
  518. """
  519. yield
  520. async def sleep(delay, result=None, *, loop=None):
  521. """Coroutine that completes after a given time (in seconds)."""
  522. if loop is not None:
  523. warnings.warn("The loop argument is deprecated since Python 3.8, "
  524. "and scheduled for removal in Python 3.10.",
  525. DeprecationWarning, stacklevel=2)
  526. if delay <= 0:
  527. await __sleep0()
  528. return result
  529. if loop is None:
  530. loop = events.get_running_loop()
  531. future = loop.create_future()
  532. h = loop.call_later(delay,
  533. futures._set_result_unless_cancelled,
  534. future, result)
  535. try:
  536. return await future
  537. finally:
  538. h.cancel()
  539. def ensure_future(coro_or_future, *, loop=None):
  540. """Wrap a coroutine or an awaitable in a future.
  541. If the argument is a Future, it is returned directly.
  542. """
  543. if coroutines.iscoroutine(coro_or_future):
  544. if loop is None:
  545. loop = events.get_event_loop()
  546. task = loop.create_task(coro_or_future)
  547. if task._source_traceback:
  548. del task._source_traceback[-1]
  549. return task
  550. elif futures.isfuture(coro_or_future):
  551. if loop is not None and loop is not futures._get_loop(coro_or_future):
  552. raise ValueError('The future belongs to a different loop than '
  553. 'the one specified as the loop argument')
  554. return coro_or_future
  555. elif inspect.isawaitable(coro_or_future):
  556. return ensure_future(_wrap_awaitable(coro_or_future), loop=loop)
  557. else:
  558. raise TypeError('An asyncio.Future, a coroutine or an awaitable is '
  559. 'required')
  560. @types.coroutine
  561. def _wrap_awaitable(awaitable):
  562. """Helper for asyncio.ensure_future().
  563. Wraps awaitable (an object with __await__) into a coroutine
  564. that will later be wrapped in a Task by ensure_future().
  565. """
  566. return (yield from awaitable.__await__())
  567. _wrap_awaitable._is_coroutine = _is_coroutine
  568. class _GatheringFuture(futures.Future):
  569. """Helper for gather().
  570. This overrides cancel() to cancel all the children and act more
  571. like Task.cancel(), which doesn't immediately mark itself as
  572. cancelled.
  573. """
  574. def __init__(self, children, *, loop=None):
  575. super().__init__(loop=loop)
  576. self._children = children
  577. self._cancel_requested = False
  578. def cancel(self, msg=None):
  579. if self.done():
  580. return False
  581. ret = False
  582. for child in self._children:
  583. if child.cancel(msg=msg):
  584. ret = True
  585. if ret:
  586. # If any child tasks were actually cancelled, we should
  587. # propagate the cancellation request regardless of
  588. # *return_exceptions* argument. See issue 32684.
  589. self._cancel_requested = True
  590. return ret
  591. def gather(*coros_or_futures, loop=None, return_exceptions=False):
  592. """Return a future aggregating results from the given coroutines/futures.
  593. Coroutines will be wrapped in a future and scheduled in the event
  594. loop. They will not necessarily be scheduled in the same order as
  595. passed in.
  596. All futures must share the same event loop. If all the tasks are
  597. done successfully, the returned future's result is the list of
  598. results (in the order of the original sequence, not necessarily
  599. the order of results arrival). If *return_exceptions* is True,
  600. exceptions in the tasks are treated the same as successful
  601. results, and gathered in the result list; otherwise, the first
  602. raised exception will be immediately propagated to the returned
  603. future.
  604. Cancellation: if the outer Future is cancelled, all children (that
  605. have not completed yet) are also cancelled. If any child is
  606. cancelled, this is treated as if it raised CancelledError --
  607. the outer Future is *not* cancelled in this case. (This is to
  608. prevent the cancellation of one child to cause other children to
  609. be cancelled.)
  610. If *return_exceptions* is False, cancelling gather() after it
  611. has been marked done won't cancel any submitted awaitables.
  612. For instance, gather can be marked done after propagating an
  613. exception to the caller, therefore, calling ``gather.cancel()``
  614. after catching an exception (raised by one of the awaitables) from
  615. gather won't cancel any other awaitables.
  616. """
  617. if loop is not None:
  618. warnings.warn("The loop argument is deprecated since Python 3.8, "
  619. "and scheduled for removal in Python 3.10.",
  620. DeprecationWarning, stacklevel=2)
  621. return _gather(*coros_or_futures, loop=loop, return_exceptions=return_exceptions)
  622. def _gather(*coros_or_futures, loop=None, return_exceptions=False):
  623. if not coros_or_futures:
  624. if loop is None:
  625. loop = events.get_event_loop()
  626. outer = loop.create_future()
  627. outer.set_result([])
  628. return outer
  629. def _done_callback(fut):
  630. nonlocal nfinished
  631. nfinished += 1
  632. if outer is None or outer.done():
  633. if not fut.cancelled():
  634. # Mark exception retrieved.
  635. fut.exception()
  636. return
  637. if not return_exceptions:
  638. if fut.cancelled():
  639. # Check if 'fut' is cancelled first, as
  640. # 'fut.exception()' will *raise* a CancelledError
  641. # instead of returning it.
  642. exc = fut._make_cancelled_error()
  643. outer.set_exception(exc)
  644. return
  645. else:
  646. exc = fut.exception()
  647. if exc is not None:
  648. outer.set_exception(exc)
  649. return
  650. if nfinished == nfuts:
  651. # All futures are done; create a list of results
  652. # and set it to the 'outer' future.
  653. results = []
  654. for fut in children:
  655. if fut.cancelled():
  656. # Check if 'fut' is cancelled first, as 'fut.exception()'
  657. # will *raise* a CancelledError instead of returning it.
  658. # Also, since we're adding the exception return value
  659. # to 'results' instead of raising it, don't bother
  660. # setting __context__. This also lets us preserve
  661. # calling '_make_cancelled_error()' at most once.
  662. res = exceptions.CancelledError(
  663. '' if fut._cancel_message is None else
  664. fut._cancel_message)
  665. else:
  666. res = fut.exception()
  667. if res is None:
  668. res = fut.result()
  669. results.append(res)
  670. if outer._cancel_requested:
  671. # If gather is being cancelled we must propagate the
  672. # cancellation regardless of *return_exceptions* argument.
  673. # See issue 32684.
  674. exc = fut._make_cancelled_error()
  675. outer.set_exception(exc)
  676. else:
  677. outer.set_result(results)
  678. arg_to_fut = {}
  679. children = []
  680. nfuts = 0
  681. nfinished = 0
  682. outer = None # bpo-46672
  683. for arg in coros_or_futures:
  684. if arg not in arg_to_fut:
  685. fut = ensure_future(arg, loop=loop)
  686. if loop is None:
  687. loop = futures._get_loop(fut)
  688. if fut is not arg:
  689. # 'arg' was not a Future, therefore, 'fut' is a new
  690. # Future created specifically for 'arg'. Since the caller
  691. # can't control it, disable the "destroy pending task"
  692. # warning.
  693. fut._log_destroy_pending = False
  694. nfuts += 1
  695. arg_to_fut[arg] = fut
  696. fut.add_done_callback(_done_callback)
  697. else:
  698. # There's a duplicate Future object in coros_or_futures.
  699. fut = arg_to_fut[arg]
  700. children.append(fut)
  701. outer = _GatheringFuture(children, loop=loop)
  702. return outer
  703. def shield(arg, *, loop=None):
  704. """Wait for a future, shielding it from cancellation.
  705. The statement
  706. res = await shield(something())
  707. is exactly equivalent to the statement
  708. res = await something()
  709. *except* that if the coroutine containing it is cancelled, the
  710. task running in something() is not cancelled. From the POV of
  711. something(), the cancellation did not happen. But its caller is
  712. still cancelled, so the yield-from expression still raises
  713. CancelledError. Note: If something() is cancelled by other means
  714. this will still cancel shield().
  715. If you want to completely ignore cancellation (not recommended)
  716. you can combine shield() with a try/except clause, as follows:
  717. try:
  718. res = await shield(something())
  719. except CancelledError:
  720. res = None
  721. """
  722. if loop is not None:
  723. warnings.warn("The loop argument is deprecated since Python 3.8, "
  724. "and scheduled for removal in Python 3.10.",
  725. DeprecationWarning, stacklevel=2)
  726. inner = ensure_future(arg, loop=loop)
  727. if inner.done():
  728. # Shortcut.
  729. return inner
  730. loop = futures._get_loop(inner)
  731. outer = loop.create_future()
  732. def _inner_done_callback(inner):
  733. if outer.cancelled():
  734. if not inner.cancelled():
  735. # Mark inner's result as retrieved.
  736. inner.exception()
  737. return
  738. if inner.cancelled():
  739. outer.cancel()
  740. else:
  741. exc = inner.exception()
  742. if exc is not None:
  743. outer.set_exception(exc)
  744. else:
  745. outer.set_result(inner.result())
  746. def _outer_done_callback(outer):
  747. if not inner.done():
  748. inner.remove_done_callback(_inner_done_callback)
  749. inner.add_done_callback(_inner_done_callback)
  750. outer.add_done_callback(_outer_done_callback)
  751. return outer
  752. def run_coroutine_threadsafe(coro, loop):
  753. """Submit a coroutine object to a given event loop.
  754. Return a concurrent.futures.Future to access the result.
  755. """
  756. if not coroutines.iscoroutine(coro):
  757. raise TypeError('A coroutine object is required')
  758. future = concurrent.futures.Future()
  759. def callback():
  760. try:
  761. futures._chain_future(ensure_future(coro, loop=loop), future)
  762. except (SystemExit, KeyboardInterrupt):
  763. raise
  764. except BaseException as exc:
  765. if future.set_running_or_notify_cancel():
  766. future.set_exception(exc)
  767. raise
  768. loop.call_soon_threadsafe(callback)
  769. return future
  770. # WeakSet containing all alive tasks.
  771. _all_tasks = weakref.WeakSet()
  772. # Dictionary containing tasks that are currently active in
  773. # all running event loops. {EventLoop: Task}
  774. _current_tasks = {}
  775. def _register_task(task):
  776. """Register a new task in asyncio as executed by loop."""
  777. _all_tasks.add(task)
  778. def _enter_task(loop, task):
  779. current_task = _current_tasks.get(loop)
  780. if current_task is not None:
  781. raise RuntimeError(f"Cannot enter into task {task!r} while another "
  782. f"task {current_task!r} is being executed.")
  783. _current_tasks[loop] = task
  784. def _leave_task(loop, task):
  785. current_task = _current_tasks.get(loop)
  786. if current_task is not task:
  787. raise RuntimeError(f"Leaving task {task!r} does not match "
  788. f"the current task {current_task!r}.")
  789. del _current_tasks[loop]
  790. def _unregister_task(task):
  791. """Unregister a task."""
  792. _all_tasks.discard(task)
  793. _py_register_task = _register_task
  794. _py_unregister_task = _unregister_task
  795. _py_enter_task = _enter_task
  796. _py_leave_task = _leave_task
  797. try:
  798. from _asyncio import (_register_task, _unregister_task,
  799. _enter_task, _leave_task,
  800. _all_tasks, _current_tasks)
  801. except ImportError:
  802. pass
  803. else:
  804. _c_register_task = _register_task
  805. _c_unregister_task = _unregister_task
  806. _c_enter_task = _enter_task
  807. _c_leave_task = _leave_task