tasks.py 33 KB

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