blob: 7e09b166ebc9be710f57ba414e7b322bce31e11c [file] [log] [blame]
R David Murray6a143812013-12-20 14:37:39 -05001.. currentmodule:: asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +01002
Yury Selivanov3faaa882018-09-14 13:32:07 -07003
4====================
5Coroutines and Tasks
Victor Stinnerea3183f2013-12-03 01:08:00 +01006====================
7
Yury Selivanov3faaa882018-09-14 13:32:07 -07008This section outlines high-level asyncio APIs to work with coroutines
9and Tasks.
lf627d2c82017-07-25 17:03:51 -060010
Yury Selivanov3faaa882018-09-14 13:32:07 -070011.. contents::
12 :depth: 1
13 :local:
14
lf627d2c82017-07-25 17:03:51 -060015
Victor Stinnerea3183f2013-12-03 01:08:00 +010016.. _coroutine:
17
18Coroutines
Yury Selivanov3faaa882018-09-14 13:32:07 -070019==========
Victor Stinnerea3183f2013-12-03 01:08:00 +010020
Yury Selivanov3faaa882018-09-14 13:32:07 -070021Coroutines declared with async/await syntax is the preferred way of
22writing asyncio applications. For example, the following snippet
23of code prints "hello", waits 1 second, and prints "world"::
Victor Stinnerea3183f2013-12-03 01:08:00 +010024
Yury Selivanov3faaa882018-09-14 13:32:07 -070025 >>> import asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +010026
Yury Selivanov3faaa882018-09-14 13:32:07 -070027 >>> async def main():
28 ... print('hello')
29 ... await asyncio.sleep(1)
30 ... print('world')
Victor Stinnerea3183f2013-12-03 01:08:00 +010031
Yury Selivanov3faaa882018-09-14 13:32:07 -070032 >>> asyncio.run(main())
33 hello
34 world
Victor Stinnerea3183f2013-12-03 01:08:00 +010035
Yury Selivanov3faaa882018-09-14 13:32:07 -070036Note that simply calling a coroutine will not schedule it to
37be executed::
Victor Stinnerea3183f2013-12-03 01:08:00 +010038
Yury Selivanov3faaa882018-09-14 13:32:07 -070039 >>> main()
40 <coroutine object main at 0x1053bb7c8>
Victor Stinnerea3183f2013-12-03 01:08:00 +010041
Yury Selivanov3faaa882018-09-14 13:32:07 -070042To actually run a coroutine asyncio provides three main mechanisms:
Victor Stinnerea3183f2013-12-03 01:08:00 +010043
Yury Selivanov3faaa882018-09-14 13:32:07 -070044* By using the :func:`asyncio.run` function to run the top-level
45 entry point "main()" function (see the above example.)
Victor Stinnerea3183f2013-12-03 01:08:00 +010046
Yury Selivanov3faaa882018-09-14 13:32:07 -070047* By awaiting on a coroutine. The following snippet of code will
48 print "hello" after waiting for 1 second, and then print "world"
49 after waiting for *another* 2 seconds::
Victor Stinnerea3183f2013-12-03 01:08:00 +010050
Yury Selivanov3faaa882018-09-14 13:32:07 -070051 import asyncio
52 import time
Victor Stinnerea3183f2013-12-03 01:08:00 +010053
Yury Selivanov3faaa882018-09-14 13:32:07 -070054 async def say_after(delay, what):
55 await asyncio.sleep(delay)
56 print(what)
57
58 async def main():
59 print('started at', time.strftime('%X'))
60
61 await say_after(1, 'hello')
62 await say_after(2, 'world')
63
64 print('finished at', time.strftime('%X'))
65
66 asyncio.run(main())
67
68 Expected output::
69
70 started at 17:13:52
71 hello
72 world
73 finished at 17:13:55
74
75* By using the :func:`asyncio.create_task` function to run coroutines
76 concurrently as asyncio :class:`Tasks <Task>`.
77
78 Let's modify the above example and run two "set_after" coroutines
79 *concurrently*::
80
81 async def main():
82 task1 = asyncio.create_task(
83 say_after(1, 'hello'))
84
85 task2 = asyncio.create_task(
86 say_after(2, 'world'))
87
88 print('started at', time.strftime('%X'))
89
90 # Wait until both tasks are completed (should take
91 # around 2 seconds.)
92 await task1
93 await task2
94
95 print('finished at', time.strftime('%X'))
96
97 Note that expected output now shows that the snippet runs
98 1 second faster than before::
99
100 started at 17:14:32
101 hello
102 world
103 finished at 17:14:34
104
105Note that in this documentation the term "coroutine" can be used for
106two closely related concepts:
107
108* a *coroutine function*: an :keyword:`async def` function;
109
110* a *coroutine object*: object returned by calling a
111 *coroutine function*.
Victor Stinner337e03f2014-08-11 01:11:13 +0200112
Victor Stinnerea3183f2013-12-03 01:08:00 +0100113
Yury Selivanov3faaa882018-09-14 13:32:07 -0700114Running an asyncio Program
115==========================
Victor Stinnerea3183f2013-12-03 01:08:00 +0100116
Elvis Pranskevichus63536bd2018-05-19 23:15:06 -0400117.. function:: run(coro, \*, debug=False)
Yury Selivanov02a0a192017-12-14 09:42:21 -0500118
119 This function runs the passed coroutine, taking care of
120 managing the asyncio event loop and finalizing asynchronous
121 generators.
122
123 This function cannot be called when another asyncio event loop is
124 running in the same thread.
125
Yury Selivanov3faaa882018-09-14 13:32:07 -0700126 If *debug* is ``True``, the event loop will be run in debug mode.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500127
128 This function always creates a new event loop and closes it at
129 the end. It should be used as a main entry point for asyncio
130 programs, and should ideally only be called once.
131
132 .. versionadded:: 3.7
Yury Selivanovd8d715f2018-05-17 13:44:00 -0400133 **Important:** this has been been added to asyncio in Python 3.7
134 on a :term:`provisional basis <provisional api>`.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500135
136
Yury Selivanov3faaa882018-09-14 13:32:07 -0700137Creating Tasks
138==============
Victor Stinnerea3183f2013-12-03 01:08:00 +0100139
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300140.. function:: create_task(coro, \*, name=None)
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200141
142 Wrap a :ref:`coroutine <coroutine>` *coro* into a task and schedule
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300143 its execution. Return the task object.
144
145 If *name* is not ``None``, it is set as the name of the task using
146 :meth:`Task.set_name`.
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200147
148 The task is executed in :func:`get_running_loop` context,
149 :exc:`RuntimeError` is raised if there is no running loop in
150 current thread.
151
152 .. versionadded:: 3.7
153
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300154 .. versionchanged:: 3.8
155 Added the ``name`` parameter.
156
Victor Stinnerea3183f2013-12-03 01:08:00 +0100157
Yury Selivanov3faaa882018-09-14 13:32:07 -0700158Sleeping
159========
Andrew Svetlovf1240162016-01-11 14:40:35 +0200160
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100161.. coroutinefunction:: sleep(delay, result=None, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100162
Yury Selivanov3faaa882018-09-14 13:32:07 -0700163 Block for *delay* seconds.
164
165 If *result* is provided, it is returned to the caller
Eli Bendersky2d26af82014-01-20 06:59:23 -0800166 when the coroutine completes.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100167
Yury Selivanov3faaa882018-09-14 13:32:07 -0700168 .. _asyncio-date-coroutine:
Victor Stinner45b27ed2014-02-01 02:36:43 +0100169
Yury Selivanov3faaa882018-09-14 13:32:07 -0700170 Example of coroutine displaying the current date every second
171 during 5 seconds::
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100172
Yury Selivanov3faaa882018-09-14 13:32:07 -0700173 import asyncio
174 import datetime
Victor Stinnerea3183f2013-12-03 01:08:00 +0100175
Yury Selivanov3faaa882018-09-14 13:32:07 -0700176 async def display_date():
177 loop = asyncio.get_running_loop()
178 end_time = loop.time() + 5.0
179 while True:
180 print(datetime.datetime.now())
181 if (loop.time() + 1.0) >= end_time:
182 break
183 await asyncio.sleep(1)
184
185 asyncio.run(display_date())
186
187
188Running Tasks Concurrently
189==========================
190
191.. coroutinefunction:: gather(\*fs, loop=None, return_exceptions=False)
192
193 Return a Future aggregating results from the given coroutine objects,
194 Tasks, or Futures.
195
196 If all Tasks/Futures are completed successfully, the result is an
197 aggregate list of returned values. The result values are in the
198 order of the original *fs* sequence.
199
200 All coroutines in the *fs* list are automatically
201 wrapped in :class:`Tasks <Task>`.
202
203 If *return_exceptions* is ``True``, exceptions in the Tasks/Futures
204 are treated the same as successful results, and gathered in the
205 result list. Otherwise, the first raised exception is immediately
206 propagated to the returned Future.
207
208 If the outer Future is *cancelled*, all submitted Tasks/Futures
209 (that have not completed yet) are also *cancelled*.
210
211 If any child is *cancelled*, it is treated as if it raised
212 :exc:`CancelledError` -- the outer Future is **not** cancelled in
213 this case. This is to prevent the cancellation of one submitted
214 Task/Future to cause other Tasks/Futures to be cancelled.
215
216 All futures must share the same event loop.
217
218 .. versionchanged:: 3.7
219 If the *gather* itself is cancelled, the cancellation is
220 propagated regardless of *return_exceptions*.
221
222 Example::
223
224 import asyncio
225
226 async def factorial(name, number):
227 f = 1
228 for i in range(2, number + 1):
229 print(f"Task {name}: Compute factorial({i})...")
230 await asyncio.sleep(1)
231 f *= i
232 print(f"Task {name}: factorial({number}) = {f}")
233
234 async def main():
235 await asyncio.gather(
236 factorial("A", 2),
237 factorial("B", 3),
238 factorial("C", 4),
239 ))
240
241 asyncio.run(main())
242
243 # Expected output:
244 #
245 # Task A: Compute factorial(2)...
246 # Task B: Compute factorial(2)...
247 # Task C: Compute factorial(2)...
248 # Task A: factorial(2) = 2
249 # Task B: Compute factorial(3)...
250 # Task C: Compute factorial(3)...
251 # Task B: factorial(3) = 6
252 # Task C: Compute factorial(4)...
253 # Task C: factorial(4) = 24
254
255
256Shielding Tasks From Cancellation
257=================================
258
259.. coroutinefunction:: shield(fut, \*, loop=None)
260
261 Wait for a Future/Task while protecting it from being cancelled.
262
263 *fut* can be a coroutine, a Task, or a Future-like object. If
264 *fut* is a coroutine it is automatically wrapped in a
265 :class:`Task`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100266
267 The statement::
268
Andrew Svetlov88743422017-12-11 17:35:49 +0200269 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100270
Yury Selivanov3faaa882018-09-14 13:32:07 -0700271 is equivalent to the statement::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100272
Andrew Svetlov88743422017-12-11 17:35:49 +0200273 res = await something()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100274
Yury Selivanov3faaa882018-09-14 13:32:07 -0700275 *except* that if the coroutine containing it is cancelled, the
276 Task running in ``something()`` is not cancelled. From the point
277 of view of ``something()``, the cancellation did not happen.
278 Although its caller is still cancelled, so the "await" expression
279 still raises :exc:`CancelledError`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100280
Yury Selivanov3faaa882018-09-14 13:32:07 -0700281 If ``something()`` is cancelled by other means (i.e. from within
282 itself) that would also cancel ``shield()``.
283
284 If it is desired to completely ignore cancellation (not recommended)
285 the ``shield()`` function should be combined with a try/except
286 clause, as follows::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100287
288 try:
Andrew Svetlov88743422017-12-11 17:35:49 +0200289 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100290 except CancelledError:
291 res = None
292
Yury Selivanov950204d2016-05-16 16:23:00 -0400293
Yury Selivanov3faaa882018-09-14 13:32:07 -0700294Timeouts
295========
296
297.. coroutinefunction:: wait_for(fut, timeout, \*, loop=None)
298
299 Wait for the coroutine, Task, or Future to complete with timeout.
300
301 *fut* can be a coroutine, a Task, or a Future-like object. If
302 *fut* is a coroutine it is automatically wrapped in a
303 :class:`Task`.
304
305 *timeout* can either be ``None`` or a float or int number of seconds
306 to wait for. If *timeout* is ``None``, block until the future
307 completes.
308
309 If a timeout occurs, it cancels the task and raises
310 :exc:`asyncio.TimeoutError`.
311
312 To avoid the task cancellation, wrap it in :func:`shield`.
313
314 The function will wait until the future is actually cancelled,
315 so the total wait time may exceed the *timeout*.
316
317 If the wait is cancelled, the future *fut* is also cancelled.
318
319 Example::
320
321 async def eternity():
322 # Sleep for one hour
323 await asyncio.sleep(3600)
324 print('yay!')
325
326 async def main():
327 # Wait for at most 1 second
328 try:
329 await asyncio.wait_for(eternity(), timeout=1.0)
330 except asyncio.TimeoutError:
331 print('timeout!')
332
333 asyncio.run(main())
334
335 # Expected output:
336 #
337 # timeout!
338
339 .. versionchanged:: 3.7
340 When *fut* is cancelled due to a timeout, ``wait_for`` waits
341 for *fut* to be cancelled. Previously, it raised
342 :exc:`asyncio.TimeoutError` immediately.
343
344
345Waiting Primitives
346==================
347
348.. coroutinefunction:: wait(fs, \*, loop=None, timeout=None,\
Andrew Svetlovf1240162016-01-11 14:40:35 +0200349 return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100350
Yury Selivanov3faaa882018-09-14 13:32:07 -0700351 Wait for a set of Futures to complete.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100352
Yury Selivanov3faaa882018-09-14 13:32:07 -0700353 *fs* is a list of coroutines, Futures, and/or Tasks. Coroutines
354 are automatically wrapped in :class:`Tasks <Task>`.
Victor Stinnerdb74d982014-06-10 11:16:05 +0200355
Yury Selivanov3faaa882018-09-14 13:32:07 -0700356 Returns two sets of Tasks/Futures: ``(done, pending)``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100357
Yury Selivanov3faaa882018-09-14 13:32:07 -0700358 *timeout* (a float or int), if specified, can be used to control
359 the maximum number of seconds to wait before returning.
360
361 Note that this function does not raise :exc:`asyncio.TimeoutError`.
362 Futures or Tasks that aren't done when the timeout occurs are just
363 returned in the second set.
364
365 *return_when* indicates when this function should return. It must
366 be one of the following constants:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100367
368 .. tabularcolumns:: |l|L|
369
370 +-----------------------------+----------------------------------------+
371 | Constant | Description |
372 +=============================+========================================+
373 | :const:`FIRST_COMPLETED` | The function will return when any |
374 | | future finishes or is cancelled. |
375 +-----------------------------+----------------------------------------+
376 | :const:`FIRST_EXCEPTION` | The function will return when any |
377 | | future finishes by raising an |
378 | | exception. If no future raises an |
379 | | exception then it is equivalent to |
380 | | :const:`ALL_COMPLETED`. |
381 +-----------------------------+----------------------------------------+
382 | :const:`ALL_COMPLETED` | The function will return when all |
383 | | futures finish or are cancelled. |
384 +-----------------------------+----------------------------------------+
385
Yury Selivanov3faaa882018-09-14 13:32:07 -0700386 Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the
387 futures when a timeout occurs.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100388
389 Usage::
390
Andrew Svetlov88743422017-12-11 17:35:49 +0200391 done, pending = await asyncio.wait(fs)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100392
Victor Stinnerea3183f2013-12-03 01:08:00 +0100393
Yury Selivanov3faaa882018-09-14 13:32:07 -0700394.. function:: as_completed(fs, \*, loop=None, timeout=None)
395
396 Return an iterator which values, when waited for, are
397 :class:`Future` instances.
398
399 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before
400 all Futures are done.
401
402 Example::
403
404 for f in as_completed(fs):
405 result = await f
406 # ...
Victor Stinnerea3183f2013-12-03 01:08:00 +0100407
Victor Stinner3e09e322013-12-03 01:22:06 +0100408
Yury Selivanov3faaa882018-09-14 13:32:07 -0700409Scheduling From Other Threads
410=============================
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100411
Yury Selivanov3faaa882018-09-14 13:32:07 -0700412.. function:: run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100413
Yury Selivanov3faaa882018-09-14 13:32:07 -0700414 Submit a coroutine to the given event loop. Thread-safe.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100415
Yury Selivanov3faaa882018-09-14 13:32:07 -0700416 Return a :class:`concurrent.futures.Future` to access the result.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100417
Yury Selivanov3faaa882018-09-14 13:32:07 -0700418 This function is meant to be called from a different OS thread
419 than the one where the event loop is running. Example::
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200420
Yury Selivanov3faaa882018-09-14 13:32:07 -0700421 # Create a coroutine
422 coro = asyncio.sleep(1, result=3)
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500423
Yury Selivanov3faaa882018-09-14 13:32:07 -0700424 # Submit the coroutine to a given loop
425 future = asyncio.run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100426
Yury Selivanov3faaa882018-09-14 13:32:07 -0700427 # Wait for the result with an optional timeout argument
428 assert future.result(timeout) == 3
429
430 If an exception is raised in the coroutine, the returned Future
431 will be notified. It can also be used to cancel the task in
432 the event loop::
433
434 try:
435 result = future.result(timeout)
436 except asyncio.TimeoutError:
437 print('The coroutine took too long, cancelling the task...')
438 future.cancel()
439 except Exception as exc:
440 print('The coroutine raised an exception: {!r}'.format(exc))
441 else:
442 print('The coroutine returned: {!r}'.format(result))
443
444 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
445 section of the documentation.
446
447 Unlike other asyncio functions this functions requires the *loop*
448 argument to be passed explicitly.
449
450 .. versionadded:: 3.5.1
451
452
453Introspection
454=============
455
456
457.. function:: current_task(loop=None)
458
459 Return the currently running :class:`Task` instance, or ``None`` if
460 no task is running.
461
462 If *loop* is ``None`` :func:`get_running_loop` is used to get
463 the current loop.
464
465 .. versionadded:: 3.7
466
467
468.. function:: all_tasks(loop=None)
469
470 Return a set of not yet finished :class:`Task` objects run by
471 the loop.
472
473 If *loop* is ``None``, :func:`get_running_loop` is used for getting
474 current loop.
475
476 .. versionadded:: 3.7
477
478
479Task Object
480===========
481
482.. class:: Task(coro, \*, loop=None, name=None)
483
484 A :class:`Future`-like object that wraps a Python
485 :ref:`coroutine <coroutine>`. Not thread-safe.
486
487 Tasks are used to run coroutines in event loops.
488 If a coroutine awaits on a Future, the Task suspends
489 the execution of the coroutine and waits for the completion
490 of the Future. When the Future is *done*, the execution of
491 the wrapped coroutine resumes.
492
493 Event loops use cooperative scheduling: an event loop runs
494 one Task at a time. While a Task awaits for the completion of a
495 Future, the event loop runs other Tasks, callbacks, or performs
496 IO operations.
497
498 Use the high-level :func:`asyncio.create_task` function to create
499 Tasks, or low-level :meth:`loop.create_task` or
500 :func:`ensure_future` functions. Manually instantiating Task
501 objects is discouraged.
502
503 To cancel a running Task use the :meth:`cancel` method. Calling it
504 will cause the Task to throw a :exc:`CancelledError` exception into
505 the wrapped coroutine. If a coroutine is awaiting on a Future
506 object during cancellation, the Future object will be cancelled.
507
508 :meth:`cancelled` can be used to check if the Task was cancelled.
509 The method returns ``True`` if the wrapped coroutine did not
510 suppress the :exc:`CancelledError` exception and was actually
511 cancelled.
512
513 :class:`asyncio.Task` inherits from :class:`Future` all of its
514 APIs except :meth:`Future.set_result` and
515 :meth:`Future.set_exception`.
516
517 Tasks support the :mod:`contextvars` module. When a Task
518 is created it copies the current context and later runs its
519 coroutine in the copied context.
Elvis Pranskevichuse2b340a2018-05-29 17:31:01 -0400520
521 .. versionchanged:: 3.7
Yury Selivanov3faaa882018-09-14 13:32:07 -0700522 Added support for the :mod:`contextvars` module.
523
524 .. versionchanged:: 3.8
525 Added the ``name`` parameter.
526
527 .. method:: cancel()
528
529 Request the Task to be cancelled.
530
531 This arranges for a :exc:`CancelledError` exception to be thrown
532 into the wrapped coroutine on the next cycle of the event loop.
533
534 The coroutine then has a chance to clean up or even deny the
535 request by suppressing the exception with a :keyword:`try` ...
536 ... ``except CancelledError`` ... :keyword:`finally` block.
537 Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does
538 not guarantee that the Task will be cancelled, although
539 suppressing cancellation completely is not common and is actively
540 discouraged.
541
542 The following example illustrates how coroutines can intercept
543 the cancellation request::
544
545 async def cancel_me():
546 print('cancel_me(): before sleep')
547
548 try:
549 # Wait for 1 hour
550 await asyncio.sleep(3600)
551 except asyncio.CancelledError:
552 print('cancel_me(): cancel sleep')
553 raise
554 finally:
555 print('cancel_me(): after sleep')
556
557 async def main():
558 # Create a "cancel_me" Task
559 task = asyncio.create_task(cancel_me())
560
561 # Wait for 1 second
562 await asyncio.sleep(1)
563
564 task.cancel()
565 try:
566 await task
567 except asyncio.CancelledError:
568 print("main(): cancel_me is cancelled now")
569
570 asyncio.run(main())
571
572 # Expected output:
573 #
574 # cancel_me(): before sleep
575 # cancel_me(): cancel sleep
576 # cancel_me(): after sleep
577 # main(): cancel_me is cancelled now
578
579 .. method:: cancelled()
580
581 Return ``True`` if the Task is *cancelled*.
582
583 The Task is *cancelled* when the cancellation was requested with
584 :meth:`cancel` and the wrapped coroutine propagated the
585 :exc:`CancelledError` exception thrown into it.
586
587 .. method:: done()
588
589 Return ``True`` if the Task is *done*.
590
591 A Task is *done* when the wrapped coroutine either returned
592 a value, raised an exception, or the Task was cancelled.
593
594 .. method:: get_stack(\*, limit=None)
595
596 Return the list of stack frames for this Task.
597
598 If the wrapped coroutine is not done, this returns the stack
599 where it is suspended. If the coroutine has completed
600 successfully or was cancelled, this returns an empty list.
601 If the coroutine was terminated by an exception, this returns
602 the list of traceback frames.
603
604 The frames are always ordered from oldest to newest.
605
606 Only one stack frame is returned for a suspended coroutine.
607
608 The optional *limit* argument sets the maximum number of frames
609 to return; by default all available frames are returned.
610 The ordering of the returned list differs depending on whether
611 a stack or a traceback is returned: the newest frames of a
612 stack are returned, but the oldest frames of a traceback are
613 returned. (This matches the behavior of the traceback module.)
614
615 .. method:: print_stack(\*, limit=None, file=None)
616
617 Print the stack or traceback for this Task.
618
619 This produces output similar to that of the traceback module
620 for the frames retrieved by :meth:`get_stack`.
621
622 The *limit* argument is passed to :meth:`get_stack` directly.
623
624 The *file* argument is an I/O stream to which the output
625 is written; by default output is written to :data:`sys.stderr`.
626
627 .. method:: get_name()
628
629 Return the name of the Task.
630
631 If no name has been explicitly assigned to the Task, the default
632 asyncio Task implementation generates a default name during
633 instantiation.
634
635 .. versionadded:: 3.8
636
637 .. method:: set_name(value)
638
639 Set the name of the Task.
640
641 The *value* argument can be any object, which is then
642 converted to a string.
643
644 In the default Task implementation, the name will be visible
645 in the :func:`repr` output of a task object.
646
647 .. versionadded:: 3.8
648
649 .. classmethod:: all_tasks(loop=None)
650
651 Return a set of all tasks for an event loop.
652
653 By default all tasks for the current event loop are returned.
654 If *loop* is ``None``, the :func:`get_event_loop` function
655 is used to get the current loop.
656
657 This function is **deprecated** and scheduled for removal in
658 Python 3.9. Use the :func:`all_tasks` function instead.
659
660 .. classmethod:: current_task(loop=None)
661
662 Return the currently running task or ``None``.
663
664 If *loop* is ``None``, the :func:`get_event_loop` function
665 is used to get the current loop.
666
667 This function is **deprecated** and scheduled for removal in
668 Python 3.9. Use the :func:`current_task` function instead.
669
670
671.. _asyncio_generator_based_coro:
672
673Generator-based Coroutines
674==========================
675
676.. note::
677
678 Support for generator-based coroutines is **deprecated** and
679 scheduled for removal in Python 4.0.
680
681Generator-based coroutines predate async/await syntax. They are
682Python generators that use ``yield from`` expression is to await
683on Futures and other coroutines.
684
685Generator-based coroutines should be decorated with
686:func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not
687enforced.
688
689
690.. decorator:: coroutine
691
692 Decorator to mark generator-based coroutines.
693
694 This decorator enables legacy generator-based coroutines to be
695 compatible with async/await code::
696
697 @asyncio.coroutine
698 def old_style_coroutine():
699 yield from asyncio.sleep(1)
700
701 async def main():
702 await old_style_coroutine()
703
704 This decorator is **deprecated** and is scheduled for removal in
705 Python 4.0.
706
707 This decorator should not be used for :keyword:`async def`
708 coroutines.
709
710.. function:: iscoroutine(obj)
711
712 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
713
714 This method is different from :func:`inspect.iscoroutine` because
715 it returns ``True`` for generator-based coroutines decorated with
716 :func:`@coroutine <coroutine>`.
717
718.. function:: iscoroutinefunction(func)
719
720 Return ``True`` if *func* is a :ref:`coroutine function
721 <coroutine>`.
722
723 This method is different from :func:`inspect.iscoroutinefunction`
724 because it returns ``True`` for generator-based coroutine functions
725 decorated with :func:`@coroutine <coroutine>`.