tasks.py 36 KB

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