tasks.py 36 KB

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