PageRenderTime 61ms CodeModel.GetById 6ms RepoModel.GetById 1ms app.codeStats 0ms

/Windows/Python3.8/WPy64-3830/WPy64-3830/python-3.8.3.amd64/Lib/asyncio/tasks.py

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