blob: 1b95592cd99ef0e4dc073bbde78a9f008ebd578e [file] [log] [blame]
R David Murray6a143812013-12-20 14:37:39 -05001.. currentmodule:: asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +01002
Yury Selivanov512d7102018-09-17 19:35:30 -04003
4====================
5Coroutines and Tasks
Victor Stinnerea3183f2013-12-03 01:08:00 +01006====================
7
Yury Selivanov512d7102018-09-17 19:35:30 -04008This section outlines high-level asyncio APIs to work with coroutines
9and Tasks.
lf627d2c82017-07-25 17:03:51 -060010
Yury Selivanov512d7102018-09-17 19:35:30 -040011.. 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 Selivanov512d7102018-09-17 19:35:30 -040019==========
Victor Stinnerea3183f2013-12-03 01:08:00 +010020
Yury Selivanov512d7102018-09-17 19:35:30 -040021Coroutines declared with async/await syntax is the preferred way of
22writing asyncio applications. For example, the following snippet
Miss Islington (bot)45452b72018-09-18 00:00:58 -070023of code (requires Python 3.7+) prints "hello", waits 1 second,
24and then prints "world"::
Victor Stinnerea3183f2013-12-03 01:08:00 +010025
Yury Selivanov512d7102018-09-17 19:35:30 -040026 >>> import asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +010027
Yury Selivanov512d7102018-09-17 19:35:30 -040028 >>> async def main():
29 ... print('hello')
30 ... await asyncio.sleep(1)
31 ... print('world')
Victor Stinnerea3183f2013-12-03 01:08:00 +010032
Yury Selivanov512d7102018-09-17 19:35:30 -040033 >>> asyncio.run(main())
34 hello
35 world
Victor Stinnerea3183f2013-12-03 01:08:00 +010036
Yury Selivanov512d7102018-09-17 19:35:30 -040037Note that simply calling a coroutine will not schedule it to
38be executed::
Victor Stinnerea3183f2013-12-03 01:08:00 +010039
Yury Selivanov512d7102018-09-17 19:35:30 -040040 >>> main()
41 <coroutine object main at 0x1053bb7c8>
Victor Stinnerea3183f2013-12-03 01:08:00 +010042
Yury Selivanov512d7102018-09-17 19:35:30 -040043To actually run a coroutine asyncio provides three main mechanisms:
Victor Stinnerea3183f2013-12-03 01:08:00 +010044
Yury Selivanov512d7102018-09-17 19:35:30 -040045* The :func:`asyncio.run` function to run the top-level
46 entry point "main()" function (see the above example.)
Victor Stinnerea3183f2013-12-03 01:08:00 +010047
Yury Selivanov512d7102018-09-17 19:35:30 -040048* Awaiting on a coroutine. The following snippet of code will
49 print "hello" after waiting for 1 second, and then print "world"
50 after waiting for *another* 2 seconds::
Victor Stinnerea3183f2013-12-03 01:08:00 +010051
Yury Selivanov512d7102018-09-17 19:35:30 -040052 import asyncio
53 import time
Victor Stinnerea3183f2013-12-03 01:08:00 +010054
Yury Selivanov512d7102018-09-17 19:35:30 -040055 async def say_after(delay, what):
56 await asyncio.sleep(delay)
57 print(what)
58
59 async def main():
60 print('started at', time.strftime('%X'))
61
62 await say_after(1, 'hello')
63 await say_after(2, 'world')
64
65 print('finished at', time.strftime('%X'))
66
67 asyncio.run(main())
68
69 Expected output::
70
71 started at 17:13:52
72 hello
73 world
74 finished at 17:13:55
75
76* The :func:`asyncio.create_task` function to run coroutines
77 concurrently as asyncio :class:`Tasks <Task>`.
78
Miss Islington (bot)9a89fd62018-09-17 23:27:07 -070079 Let's modify the above example and run two ``say_after`` coroutines
Yury Selivanov512d7102018-09-17 19:35:30 -040080 *concurrently*::
81
82 async def main():
83 task1 = asyncio.create_task(
84 say_after(1, 'hello'))
85
86 task2 = asyncio.create_task(
87 say_after(2, 'world'))
88
89 print('started at', time.strftime('%X'))
90
91 # Wait until both tasks are completed (should take
92 # around 2 seconds.)
93 await task1
94 await task2
95
96 print('finished at', time.strftime('%X'))
97
98 Note that expected output now shows that the snippet runs
99 1 second faster than before::
100
101 started at 17:14:32
102 hello
103 world
104 finished at 17:14:34
105
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700106
107.. _asyncio-awaitables:
108
109Awaitables
110==========
111
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700112We say that an object is an **awaitable** object if it can be used
113in an :keyword:`await` expression. Many asyncio APIs are designed to
114accept awaitables.
115
116There are three main types of *awaitable* objects:
117**coroutines**, **Tasks**, and **Futures**.
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700118
119
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700120.. rubric:: Coroutines
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700121
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700122Python coroutines are *awaitables* and therefore can be awaited from
123other coroutines::
124
125 import asyncio
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700126
127 async def nested():
128 return 42
129
130 async def main():
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700131 # Nothing happens if we just call "nested()".
132 # (a coroutine object is created but not awaited)
133 nested()
134
135 # Let's do it differently now and await it:
136 print(await nested()) # will print "42".
137
138 asyncio.run(main())
139
140.. important::
141
142 In this documentation the term "coroutine" can be used for
143 two closely related concepts:
144
145 * a *coroutine function*: an :keyword:`async def` function;
146
147 * a *coroutine object*: an object returned by calling a
148 *coroutine function*.
149
150asyncio also supports legacy :ref:`generator-based
151<asyncio_generator_based_coro>` coroutines.
152
153
154.. rubric:: Tasks
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700155
156*Tasks* are used to schedule coroutines *concurrently*.
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700157
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700158When a coroutine is wrapped into a *Task* with functions like
159:func:`asyncio.create_task` the coroutine is automatically
160scheduled to run soon::
Yury Selivanov512d7102018-09-17 19:35:30 -0400161
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700162 import asyncio
Yury Selivanov512d7102018-09-17 19:35:30 -0400163
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700164 async def nested():
165 return 42
166
167 async def main():
168 # Schedule nested() to run soon concurrently
169 # with "main()".
170 task = asyncio.create_task(nested())
171
172 # "task" can now be used to cancel "nested()", or
173 # can simply be awaited to wait until it is complete:
174 await task
175
176 asyncio.run(main())
Victor Stinner337e03f2014-08-11 01:11:13 +0200177
Victor Stinnerea3183f2013-12-03 01:08:00 +0100178
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700179.. rubric:: Futures
180
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700181A :class:`Future` is a special **low-level** awaitable object that
182represents an **eventual result** of an asynchronous operation.
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700183
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700184When a Future object is *awaited* it means that the coroutine will
185wait until the Future is resolved in some other place.
186
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700187Future objects in asyncio are needed to allow callback-based code
188to be used with async/await.
189
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700190Normally **there is no need** to create Future objects at the
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700191application level code.
192
193Future objects, sometimes exposed by libraries and some asyncio
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700194APIs, can be awaited::
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700195
196 async def main():
197 await function_that_returns_a_future_object()
198
199 # this is also valid:
200 await asyncio.gather(
201 function_that_returns_a_future_object(),
202 some_python_coroutine()
203 )
204
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700205A good example of a low-level function that returns a Future object
206is :meth:`loop.run_in_executor`.
207
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700208
Yury Selivanov512d7102018-09-17 19:35:30 -0400209Running an asyncio Program
210==========================
Victor Stinnerea3183f2013-12-03 01:08:00 +0100211
Elvis Pranskevichus15f3d0c2018-05-19 23:39:45 -0400212.. function:: run(coro, \*, debug=False)
Yury Selivanov02a0a192017-12-14 09:42:21 -0500213
214 This function runs the passed coroutine, taking care of
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700215 managing the asyncio event loop and *finalizing asynchronous
216 generators*.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500217
218 This function cannot be called when another asyncio event loop is
219 running in the same thread.
220
Yury Selivanov512d7102018-09-17 19:35:30 -0400221 If *debug* is ``True``, the event loop will be run in debug mode.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500222
223 This function always creates a new event loop and closes it at
224 the end. It should be used as a main entry point for asyncio
225 programs, and should ideally only be called once.
226
227 .. versionadded:: 3.7
Yury Selivanov512d7102018-09-17 19:35:30 -0400228 **Important:** this function has been added to asyncio in
229 Python 3.7 on a :term:`provisional basis <provisional api>`.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500230
231
Yury Selivanov512d7102018-09-17 19:35:30 -0400232Creating Tasks
233==============
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100234
Yury Selivanov512d7102018-09-17 19:35:30 -0400235.. function:: create_task(coro)
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100236
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700237 Wrap the *coro* :ref:`coroutine <coroutine>` into a :class:`Task`
238 and schedule its execution. Return the Task object.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100239
Yury Selivanov512d7102018-09-17 19:35:30 -0400240 The task is executed in the loop returned by :func:`get_running_loop`,
241 :exc:`RuntimeError` is raised if there is no running loop in
242 current thread.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100243
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700244 This function has been **added in Python 3.7**. Prior to
245 Python 3.7, the low-level :func:`asyncio.ensure_future` function
246 can be used instead::
247
248 async def coro():
249 ...
250
251 # In Python 3.7+
252 task = asyncio.create_task(coro())
253 ...
254
255 # This works in all Python versions but is less readable
256 task = asyncio.ensure_future(coro())
257 ...
258
Yury Selivanov512d7102018-09-17 19:35:30 -0400259 .. versionadded:: 3.7
Victor Stinner7f314ed2014-10-15 18:49:16 +0200260
261
Yury Selivanov512d7102018-09-17 19:35:30 -0400262Sleeping
263========
Victor Stinner7f314ed2014-10-15 18:49:16 +0200264
Yury Selivanov512d7102018-09-17 19:35:30 -0400265.. coroutinefunction:: sleep(delay, result=None, \*, loop=None)
Victor Stinner7f314ed2014-10-15 18:49:16 +0200266
Yury Selivanov512d7102018-09-17 19:35:30 -0400267 Block for *delay* seconds.
268
269 If *result* is provided, it is returned to the caller
270 when the coroutine completes.
271
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700272 The *loop* argument is deprecated and scheduled for removal
273 in Python 4.0.
274
Yury Selivanov512d7102018-09-17 19:35:30 -0400275 .. _asyncio_example_sleep:
276
277 Example of coroutine displaying the current date every second
278 for 5 seconds::
Victor Stinner7f314ed2014-10-15 18:49:16 +0200279
280 import asyncio
281 import datetime
282
Yury Selivanov02a0a192017-12-14 09:42:21 -0500283 async def display_date():
284 loop = asyncio.get_running_loop()
Yury Selivanov66f88282015-06-24 11:04:15 -0400285 end_time = loop.time() + 5.0
286 while True:
287 print(datetime.datetime.now())
288 if (loop.time() + 1.0) >= end_time:
289 break
290 await asyncio.sleep(1)
291
Yury Selivanov02a0a192017-12-14 09:42:21 -0500292 asyncio.run(display_date())
Yury Selivanov66f88282015-06-24 11:04:15 -0400293
Victor Stinner7f314ed2014-10-15 18:49:16 +0200294
Yury Selivanov512d7102018-09-17 19:35:30 -0400295Running Tasks Concurrently
296==========================
Victor Stinner7f314ed2014-10-15 18:49:16 +0200297
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700298.. awaitablefunction:: gather(\*aws, loop=None, return_exceptions=False)
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100299
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700300 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700301 sequence *concurrently*.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100302
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700303 If any awaitable in *aws* is a coroutine, it is automatically
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700304 scheduled as a Task.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100305
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700306 If all awaitables are completed successfully, the result is an
307 aggregate list of returned values. The order of result values
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700308 corresponds to the order of awaitables in *aws*.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100309
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700310 If *return_exceptions* is ``True``, exceptions are treated the
311 same as successful results, and aggregated in the result list.
312 Otherwise, the first raised exception is immediately propagated
313 to the task that awaits on ``gather()``.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100314
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700315 If ``gather`` is *cancelled*, all submitted awaitables
Yury Selivanov512d7102018-09-17 19:35:30 -0400316 (that have not completed yet) are also *cancelled*.
Victor Stinnerb69d62d2013-12-10 02:09:46 +0100317
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700318 If any Task or Future from the *aws* sequence is *cancelled*, it is
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700319 treated as if it raised :exc:`CancelledError` -- the ``gather()``
320 call is **not** cancelled in this case. This is to prevent the
321 cancellation of one submitted Task/Future to cause other
322 Tasks/Futures to be cancelled.
Miss Islington (bot)2fc443c2018-05-23 10:59:17 -0700323
Yury Selivanov512d7102018-09-17 19:35:30 -0400324 .. _asyncio_example_gather:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100325
326 Example::
327
Yury Selivanov512d7102018-09-17 19:35:30 -0400328 import asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +0100329
Yury Selivanov512d7102018-09-17 19:35:30 -0400330 async def factorial(name, number):
331 f = 1
332 for i in range(2, number + 1):
333 print(f"Task {name}: Compute factorial({i})...")
334 await asyncio.sleep(1)
335 f *= i
336 print(f"Task {name}: factorial({number}) = {f}")
Victor Stinnerea3183f2013-12-03 01:08:00 +0100337
Yury Selivanov512d7102018-09-17 19:35:30 -0400338 async def main():
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700339 # Schedule three calls *concurrently*:
Yury Selivanov512d7102018-09-17 19:35:30 -0400340 await asyncio.gather(
341 factorial("A", 2),
342 factorial("B", 3),
343 factorial("C", 4),
Miss Islington (bot)ee2ff1a2018-09-17 23:27:27 -0700344 )
Victor Stinnerea3183f2013-12-03 01:08:00 +0100345
Yury Selivanov512d7102018-09-17 19:35:30 -0400346 asyncio.run(main())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100347
Yury Selivanov512d7102018-09-17 19:35:30 -0400348 # Expected output:
349 #
350 # Task A: Compute factorial(2)...
351 # Task B: Compute factorial(2)...
352 # Task C: Compute factorial(2)...
353 # Task A: factorial(2) = 2
354 # Task B: Compute factorial(3)...
355 # Task C: Compute factorial(3)...
356 # Task B: factorial(3) = 6
357 # Task C: Compute factorial(4)...
358 # Task C: factorial(4) = 24
Victor Stinnerea3183f2013-12-03 01:08:00 +0100359
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700360 .. versionchanged:: 3.7
361 If the *gather* itself is cancelled, the cancellation is
362 propagated regardless of *return_exceptions*.
363
Victor Stinnerea3183f2013-12-03 01:08:00 +0100364
Yury Selivanov512d7102018-09-17 19:35:30 -0400365Shielding Tasks From Cancellation
366=================================
Yury Selivanovd7e19bb2015-05-11 16:33:41 -0400367
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700368.. awaitablefunction:: shield(aw, \*, loop=None)
Yury Selivanove319ab02015-12-15 00:45:24 -0500369
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700370 Protect an :ref:`awaitable object <asyncio-awaitables>`
371 from being :meth:`cancelled <Task.cancel>`.
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200372
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700373 *aw* can be a coroutine, a Task, or a Future-like object. If
374 *aw* is a coroutine it is automatically scheduled as a Task.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100375
376 The statement::
377
Andrew Svetlov88743422017-12-11 17:35:49 +0200378 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100379
Yury Selivanov512d7102018-09-17 19:35:30 -0400380 is equivalent to::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100381
Andrew Svetlov88743422017-12-11 17:35:49 +0200382 res = await something()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100383
Yury Selivanov512d7102018-09-17 19:35:30 -0400384 *except* that if the coroutine containing it is cancelled, the
385 Task running in ``something()`` is not cancelled. From the point
386 of view of ``something()``, the cancellation did not happen.
387 Although its caller is still cancelled, so the "await" expression
388 still raises a :exc:`CancelledError`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100389
Yury Selivanov512d7102018-09-17 19:35:30 -0400390 If ``something()`` is cancelled by other means (i.e. from within
391 itself) that would also cancel ``shield()``.
392
393 If it is desired to completely ignore cancellation (not recommended)
394 the ``shield()`` function should be combined with a try/except
395 clause, as follows::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100396
397 try:
Andrew Svetlov88743422017-12-11 17:35:49 +0200398 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100399 except CancelledError:
400 res = None
401
Yury Selivanov950204d2016-05-16 16:23:00 -0400402
Yury Selivanov512d7102018-09-17 19:35:30 -0400403Timeouts
404========
405
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700406.. coroutinefunction:: wait_for(aw, timeout, \*, loop=None)
Yury Selivanov512d7102018-09-17 19:35:30 -0400407
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700408 Wait for the *aw* :ref:`awaitable <asyncio-awaitables>`
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700409 to complete with a timeout.
Yury Selivanov512d7102018-09-17 19:35:30 -0400410
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700411 If *aw* is a coroutine it is automatically scheduled as a Task.
Yury Selivanov512d7102018-09-17 19:35:30 -0400412
413 *timeout* can either be ``None`` or a float or int number of seconds
414 to wait for. If *timeout* is ``None``, block until the future
415 completes.
416
417 If a timeout occurs, it cancels the task and raises
418 :exc:`asyncio.TimeoutError`.
419
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700420 To avoid the task :meth:`cancellation <Task.cancel>`,
421 wrap it in :func:`shield`.
Yury Selivanov512d7102018-09-17 19:35:30 -0400422
423 The function will wait until the future is actually cancelled,
424 so the total wait time may exceed the *timeout*.
425
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700426 If the wait is cancelled, the future *aw* is also cancelled.
Yury Selivanov512d7102018-09-17 19:35:30 -0400427
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700428 The *loop* argument is deprecated and scheduled for removal
429 in Python 4.0.
430
Yury Selivanov512d7102018-09-17 19:35:30 -0400431 .. _asyncio_example_waitfor:
432
433 Example::
434
435 async def eternity():
436 # Sleep for one hour
437 await asyncio.sleep(3600)
438 print('yay!')
439
440 async def main():
441 # Wait for at most 1 second
442 try:
443 await asyncio.wait_for(eternity(), timeout=1.0)
444 except asyncio.TimeoutError:
445 print('timeout!')
446
447 asyncio.run(main())
448
449 # Expected output:
450 #
451 # timeout!
452
453 .. versionchanged:: 3.7
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700454 When *aw* is cancelled due to a timeout, ``wait_for`` waits
455 for *aw* to be cancelled. Previously, it raised
Yury Selivanov512d7102018-09-17 19:35:30 -0400456 :exc:`asyncio.TimeoutError` immediately.
457
458
459Waiting Primitives
460==================
461
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700462.. coroutinefunction:: wait(aws, \*, loop=None, timeout=None,\
Andrew Svetlovf1240162016-01-11 14:40:35 +0200463 return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100464
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700465 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700466 sequence concurrently and block until the condition specified
467 by *return_when*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100468
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700469 If any awaitable in *aws* is a coroutine, it is automatically
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700470 scheduled as a Task.
Victor Stinnerdb74d982014-06-10 11:16:05 +0200471
Yury Selivanov512d7102018-09-17 19:35:30 -0400472 Returns two sets of Tasks/Futures: ``(done, pending)``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100473
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700474 The *loop* argument is deprecated and scheduled for removal
475 in Python 4.0.
476
Yury Selivanov512d7102018-09-17 19:35:30 -0400477 *timeout* (a float or int), if specified, can be used to control
478 the maximum number of seconds to wait before returning.
479
480 Note that this function does not raise :exc:`asyncio.TimeoutError`.
481 Futures or Tasks that aren't done when the timeout occurs are simply
482 returned in the second set.
483
484 *return_when* indicates when this function should return. It must
485 be one of the following constants:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100486
487 .. tabularcolumns:: |l|L|
488
489 +-----------------------------+----------------------------------------+
490 | Constant | Description |
491 +=============================+========================================+
492 | :const:`FIRST_COMPLETED` | The function will return when any |
493 | | future finishes or is cancelled. |
494 +-----------------------------+----------------------------------------+
495 | :const:`FIRST_EXCEPTION` | The function will return when any |
496 | | future finishes by raising an |
497 | | exception. If no future raises an |
498 | | exception then it is equivalent to |
499 | | :const:`ALL_COMPLETED`. |
500 +-----------------------------+----------------------------------------+
501 | :const:`ALL_COMPLETED` | The function will return when all |
502 | | futures finish or are cancelled. |
503 +-----------------------------+----------------------------------------+
504
Yury Selivanov512d7102018-09-17 19:35:30 -0400505 Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the
506 futures when a timeout occurs.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100507
508 Usage::
509
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700510 done, pending = await asyncio.wait(aws)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100511
Victor Stinnerea3183f2013-12-03 01:08:00 +0100512
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700513.. function:: as_completed(aws, \*, loop=None, timeout=None)
Yury Selivanov512d7102018-09-17 19:35:30 -0400514
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700515 Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700516 set concurrently. Return an iterator of :class:`Future` objects.
517 Each Future object returned represents the earliest result
518 from the set of the remaining awaitables.
Yury Selivanov512d7102018-09-17 19:35:30 -0400519
520 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before
521 all Futures are done.
522
523 Example::
524
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700525 for f in as_completed(aws):
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700526 earliest_result = await f
Yury Selivanov512d7102018-09-17 19:35:30 -0400527 # ...
Victor Stinnerea3183f2013-12-03 01:08:00 +0100528
Victor Stinner3e09e322013-12-03 01:22:06 +0100529
Yury Selivanov512d7102018-09-17 19:35:30 -0400530Scheduling From Other Threads
531=============================
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100532
Yury Selivanov512d7102018-09-17 19:35:30 -0400533.. function:: run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100534
Yury Selivanov512d7102018-09-17 19:35:30 -0400535 Submit a coroutine to the given event loop. Thread-safe.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100536
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700537 Return a :class:`concurrent.futures.Future` to wait for the result
538 from another OS thread.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100539
Yury Selivanov512d7102018-09-17 19:35:30 -0400540 This function is meant to be called from a different OS thread
541 than the one where the event loop is running. Example::
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200542
Yury Selivanov512d7102018-09-17 19:35:30 -0400543 # Create a coroutine
544 coro = asyncio.sleep(1, result=3)
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500545
Yury Selivanov512d7102018-09-17 19:35:30 -0400546 # Submit the coroutine to a given loop
547 future = asyncio.run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100548
Yury Selivanov512d7102018-09-17 19:35:30 -0400549 # Wait for the result with an optional timeout argument
550 assert future.result(timeout) == 3
551
552 If an exception is raised in the coroutine, the returned Future
553 will be notified. It can also be used to cancel the task in
554 the event loop::
555
556 try:
557 result = future.result(timeout)
558 except asyncio.TimeoutError:
559 print('The coroutine took too long, cancelling the task...')
560 future.cancel()
561 except Exception as exc:
562 print('The coroutine raised an exception: {!r}'.format(exc))
563 else:
564 print('The coroutine returned: {!r}'.format(result))
565
566 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
567 section of the documentation.
568
569 Unlike other asyncio functions this functions requires the *loop*
570 argument to be passed explicitly.
571
572 .. versionadded:: 3.5.1
573
574
575Introspection
576=============
577
578
579.. function:: current_task(loop=None)
580
581 Return the currently running :class:`Task` instance, or ``None`` if
582 no task is running.
583
584 If *loop* is ``None`` :func:`get_running_loop` is used to get
585 the current loop.
586
587 .. versionadded:: 3.7
588
589
590.. function:: all_tasks(loop=None)
591
592 Return a set of not yet finished :class:`Task` objects run by
593 the loop.
594
595 If *loop* is ``None``, :func:`get_running_loop` is used for getting
596 current loop.
597
598 .. versionadded:: 3.7
599
600
601Task Object
602===========
603
604.. class:: Task(coro, \*, loop=None)
605
606 A :class:`Future`-like object that wraps a Python
607 :ref:`coroutine <coroutine>`. Not thread-safe.
608
609 Tasks are used to run coroutines in event loops.
610 If a coroutine awaits on a Future, the Task suspends
611 the execution of the coroutine and waits for the completion
612 of the Future. When the Future is *done*, the execution of
613 the wrapped coroutine resumes.
614
615 Event loops use cooperative scheduling: an event loop runs
616 one Task at a time. While a Task awaits for the completion of a
617 Future, the event loop runs other Tasks, callbacks, or performs
618 IO operations.
619
620 Use the high-level :func:`asyncio.create_task` function to create
621 Tasks, or the low-level :meth:`loop.create_task` or
622 :func:`ensure_future` functions. Manual instantiation of Tasks
623 is discouraged.
624
625 To cancel a running Task use the :meth:`cancel` method. Calling it
626 will cause the Task to throw a :exc:`CancelledError` exception into
627 the wrapped coroutine. If a coroutine is awaiting on a Future
628 object during cancellation, the Future object will be cancelled.
629
630 :meth:`cancelled` can be used to check if the Task was cancelled.
631 The method returns ``True`` if the wrapped coroutine did not
632 suppress the :exc:`CancelledError` exception and was actually
633 cancelled.
634
635 :class:`asyncio.Task` inherits from :class:`Future` all of its
636 APIs except :meth:`Future.set_result` and
637 :meth:`Future.set_exception`.
638
639 Tasks support the :mod:`contextvars` module. When a Task
640 is created it copies the current context and later runs its
641 coroutine in the copied context.
Miss Islington (bot)d8948c52018-05-29 15:37:06 -0700642
643 .. versionchanged:: 3.7
Yury Selivanov512d7102018-09-17 19:35:30 -0400644 Added support for the :mod:`contextvars` module.
645
646 .. method:: cancel()
647
648 Request the Task to be cancelled.
649
650 This arranges for a :exc:`CancelledError` exception to be thrown
651 into the wrapped coroutine on the next cycle of the event loop.
652
653 The coroutine then has a chance to clean up or even deny the
654 request by suppressing the exception with a :keyword:`try` ...
655 ... ``except CancelledError`` ... :keyword:`finally` block.
656 Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does
657 not guarantee that the Task will be cancelled, although
658 suppressing cancellation completely is not common and is actively
659 discouraged.
660
661 .. _asyncio_example_task_cancel:
662
663 The following example illustrates how coroutines can intercept
664 the cancellation request::
665
666 async def cancel_me():
667 print('cancel_me(): before sleep')
668
669 try:
670 # Wait for 1 hour
671 await asyncio.sleep(3600)
672 except asyncio.CancelledError:
673 print('cancel_me(): cancel sleep')
674 raise
675 finally:
676 print('cancel_me(): after sleep')
677
678 async def main():
679 # Create a "cancel_me" Task
680 task = asyncio.create_task(cancel_me())
681
682 # Wait for 1 second
683 await asyncio.sleep(1)
684
685 task.cancel()
686 try:
687 await task
688 except asyncio.CancelledError:
689 print("main(): cancel_me is cancelled now")
690
691 asyncio.run(main())
692
693 # Expected output:
694 #
695 # cancel_me(): before sleep
696 # cancel_me(): cancel sleep
697 # cancel_me(): after sleep
698 # main(): cancel_me is cancelled now
699
700 .. method:: cancelled()
701
702 Return ``True`` if the Task is *cancelled*.
703
704 The Task is *cancelled* when the cancellation was requested with
705 :meth:`cancel` and the wrapped coroutine propagated the
706 :exc:`CancelledError` exception thrown into it.
707
708 .. method:: done()
709
710 Return ``True`` if the Task is *done*.
711
712 A Task is *done* when the wrapped coroutine either returned
713 a value, raised an exception, or the Task was cancelled.
714
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700715 .. method:: result()
716
717 Return the result of the Task.
718
719 If the Task is *done*, the result of the wrapped coroutine
720 is returned (or if the coroutine raised an exception, that
721 exception is re-raised.)
722
723 If the Task has been *cancelled*, this method raises
724 a :exc:`CancelledError` exception.
725
726 If the Task's result isn't yet available, this method raises
727 a :exc:`InvalidStateError` exception.
728
729 .. method:: exception()
730
731 Return the exception of the Task.
732
733 If the wrapped coroutine raised an exception that exception
734 is returned. If the wrapped coroutine returned normally
735 this method returns ``None``.
736
737 If the Task has been *cancelled*, this method raises a
738 :exc:`CancelledError` exception.
739
740 If the Task isn't *done* yet, this method raises an
741 :exc:`InvalidStateError` exception.
742
743 .. method:: add_done_callback(callback, *, context=None)
744
745 Add a callback to be run when the Task is *done*.
746
747 This method should only be used in low-level callback-based code.
748
749 See the documentation of :meth:`Future.add_done_callback`
750 for more details.
751
752 .. method:: remove_done_callback(callback)
753
754 Remove *callback* from the callbacks list.
755
756 This method should only be used in low-level callback-based code.
757
758 See the documentation of :meth:`Future.remove_done_callback`
759 for more details.
760
Yury Selivanov512d7102018-09-17 19:35:30 -0400761 .. method:: get_stack(\*, limit=None)
762
763 Return the list of stack frames for this Task.
764
765 If the wrapped coroutine is not done, this returns the stack
766 where it is suspended. If the coroutine has completed
767 successfully or was cancelled, this returns an empty list.
768 If the coroutine was terminated by an exception, this returns
769 the list of traceback frames.
770
771 The frames are always ordered from oldest to newest.
772
773 Only one stack frame is returned for a suspended coroutine.
774
775 The optional *limit* argument sets the maximum number of frames
776 to return; by default all available frames are returned.
777 The ordering of the returned list differs depending on whether
778 a stack or a traceback is returned: the newest frames of a
779 stack are returned, but the oldest frames of a traceback are
780 returned. (This matches the behavior of the traceback module.)
781
782 .. method:: print_stack(\*, limit=None, file=None)
783
784 Print the stack or traceback for this Task.
785
786 This produces output similar to that of the traceback module
787 for the frames retrieved by :meth:`get_stack`.
788
789 The *limit* argument is passed to :meth:`get_stack` directly.
790
791 The *file* argument is an I/O stream to which the output
792 is written; by default output is written to :data:`sys.stderr`.
793
794 .. classmethod:: all_tasks(loop=None)
795
796 Return a set of all tasks for an event loop.
797
798 By default all tasks for the current event loop are returned.
799 If *loop* is ``None``, the :func:`get_event_loop` function
800 is used to get the current loop.
801
802 This method is **deprecated** and will be removed in
803 Python 3.9. Use the :func:`all_tasks` function instead.
804
805 .. classmethod:: current_task(loop=None)
806
807 Return the currently running task or ``None``.
808
809 If *loop* is ``None``, the :func:`get_event_loop` function
810 is used to get the current loop.
811
812 This method is **deprecated** and will be removed in
813 Python 3.9. Use the :func:`current_task` function instead.
814
815
816.. _asyncio_generator_based_coro:
817
818Generator-based Coroutines
819==========================
820
821.. note::
822
823 Support for generator-based coroutines is **deprecated** and
824 is scheduled for removal in Python 4.0.
825
826Generator-based coroutines predate async/await syntax. They are
827Python generators that use ``yield from`` expressions to await
828on Futures and other coroutines.
829
830Generator-based coroutines should be decorated with
831:func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not
832enforced.
833
834
835.. decorator:: coroutine
836
837 Decorator to mark generator-based coroutines.
838
839 This decorator enables legacy generator-based coroutines to be
840 compatible with async/await code::
841
842 @asyncio.coroutine
843 def old_style_coroutine():
844 yield from asyncio.sleep(1)
845
846 async def main():
847 await old_style_coroutine()
848
849 This decorator is **deprecated** and is scheduled for removal in
850 Python 4.0.
851
852 This decorator should not be used for :keyword:`async def`
853 coroutines.
854
855.. function:: iscoroutine(obj)
856
857 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
858
859 This method is different from :func:`inspect.iscoroutine` because
860 it returns ``True`` for generator-based coroutines decorated with
861 :func:`@coroutine <coroutine>`.
862
863.. function:: iscoroutinefunction(func)
864
865 Return ``True`` if *func* is a :ref:`coroutine function
866 <coroutine>`.
867
868 This method is different from :func:`inspect.iscoroutinefunction`
869 because it returns ``True`` for generator-based coroutine functions
870 decorated with :func:`@coroutine <coroutine>`.