Debian Codegraph @

lib-python/3/asyncio/tasks.py

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