blob: 85292a61ecd6d8aa2b3e2368badb2b129749bd96 [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
Yury Selivanovb042cf12018-09-18 02:47:54 -040023of code (requires Python 3.7+) prints "hello", waits 1 second,
24and then prints "world"::
Victor Stinnerea3183f2013-12-03 01:08:00 +010025
Yury Selivanov3faaa882018-09-14 13:32:07 -070026 >>> import asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +010027
Yury Selivanov3faaa882018-09-14 13:32:07 -070028 >>> async def main():
29 ... print('hello')
30 ... await asyncio.sleep(1)
31 ... print('world')
Victor Stinnerea3183f2013-12-03 01:08:00 +010032
Yury Selivanov3faaa882018-09-14 13:32:07 -070033 >>> asyncio.run(main())
34 hello
35 world
Victor Stinnerea3183f2013-12-03 01:08:00 +010036
Yury Selivanov3faaa882018-09-14 13:32:07 -070037Note that simply calling a coroutine will not schedule it to
38be executed::
Victor Stinnerea3183f2013-12-03 01:08:00 +010039
Yury Selivanov3faaa882018-09-14 13:32:07 -070040 >>> main()
41 <coroutine object main at 0x1053bb7c8>
Victor Stinnerea3183f2013-12-03 01:08:00 +010042
Yury Selivanov3faaa882018-09-14 13:32:07 -070043To actually run a coroutine asyncio provides three main mechanisms:
Victor Stinnerea3183f2013-12-03 01:08:00 +010044
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040045* The :func:`asyncio.run` function to run the top-level
Yury Selivanov3faaa882018-09-14 13:32:07 -070046 entry point "main()" function (see the above example.)
Victor Stinnerea3183f2013-12-03 01:08:00 +010047
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040048* Awaiting on a coroutine. The following snippet of code will
Yury Selivanov3faaa882018-09-14 13:32:07 -070049 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 Selivanov3faaa882018-09-14 13:32:07 -070052 import asyncio
53 import time
Victor Stinnerea3183f2013-12-03 01:08:00 +010054
Yury Selivanov3faaa882018-09-14 13:32:07 -070055 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
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040076* The :func:`asyncio.create_task` function to run coroutines
Yury Selivanov3faaa882018-09-14 13:32:07 -070077 concurrently as asyncio :class:`Tasks <Task>`.
78
Danny Hermes7bfbda42018-09-17 21:49:21 -070079 Let's modify the above example and run two ``say_after`` coroutines
Yury Selivanov3faaa882018-09-14 13:32:07 -070080 *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
Yury Selivanov47150392018-09-18 17:55:44 -0400106
107.. _asyncio-awaitables:
108
109Awaitables
110==========
111
112We say that an object is an *awaitable* object if it can be used
113in an :keyword:`await` expression.
114
115
116.. rubric:: Coroutines and Tasks
117
118Python coroutines are *awaitables*::
119
120 async def nested():
121 return 42
122
123 async def main():
124 # Will print "42":
125 print(await nested())
126
127*Tasks* are used to schedule coroutines *concurrently*.
128See the previous :ref:`section <coroutine>` for an introduction
129to coroutines and tasks.
130
Yury Selivanov3faaa882018-09-14 13:32:07 -0700131Note that in this documentation the term "coroutine" can be used for
132two closely related concepts:
133
134* a *coroutine function*: an :keyword:`async def` function;
135
136* a *coroutine object*: object returned by calling a
137 *coroutine function*.
Victor Stinner337e03f2014-08-11 01:11:13 +0200138
Victor Stinnerea3183f2013-12-03 01:08:00 +0100139
Yury Selivanov47150392018-09-18 17:55:44 -0400140.. rubric:: Futures
141
142There is a dedicated section about the :ref:`asyncio Future object
143<asyncio-futures>`, but the concept is fundamental to asyncio so
144it needs a brief introduction in this section.
145
146A Future is a special **low-level** awaitable object that represents
147an **eventual result** of an asynchronous operation.
148Future objects in asyncio are needed to allow callback-based code
149to be used with async/await.
150
151Normally, **there is no need** to create Future objects at the
152application level code.
153
154Future objects, sometimes exposed by libraries and some asyncio
155APIs, should be awaited::
156
157 async def main():
158 await function_that_returns_a_future_object()
159
160 # this is also valid:
161 await asyncio.gather(
162 function_that_returns_a_future_object(),
163 some_python_coroutine()
164 )
165
166
Yury Selivanov3faaa882018-09-14 13:32:07 -0700167Running an asyncio Program
168==========================
Victor Stinnerea3183f2013-12-03 01:08:00 +0100169
Elvis Pranskevichus63536bd2018-05-19 23:15:06 -0400170.. function:: run(coro, \*, debug=False)
Yury Selivanov02a0a192017-12-14 09:42:21 -0500171
172 This function runs the passed coroutine, taking care of
Yury Selivanov47150392018-09-18 17:55:44 -0400173 managing the asyncio event loop and *finalizing asynchronous
174 generators*.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500175
176 This function cannot be called when another asyncio event loop is
177 running in the same thread.
178
Yury Selivanov3faaa882018-09-14 13:32:07 -0700179 If *debug* is ``True``, the event loop will be run in debug mode.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500180
181 This function always creates a new event loop and closes it at
182 the end. It should be used as a main entry point for asyncio
183 programs, and should ideally only be called once.
184
185 .. versionadded:: 3.7
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400186 **Important:** this function has been added to asyncio in
187 Python 3.7 on a :term:`provisional basis <provisional api>`.
Yury Selivanov02a0a192017-12-14 09:42:21 -0500188
189
Yury Selivanov3faaa882018-09-14 13:32:07 -0700190Creating Tasks
191==============
Victor Stinnerea3183f2013-12-03 01:08:00 +0100192
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300193.. function:: create_task(coro, \*, name=None)
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200194
Yury Selivanov47150392018-09-18 17:55:44 -0400195 Wrap the *coro* :ref:`coroutine <coroutine>` into a Task and
196 schedule its execution. Return the Task object.
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300197
198 If *name* is not ``None``, it is set as the name of the task using
199 :meth:`Task.set_name`.
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200200
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400201 The task is executed in the loop returned by :func:`get_running_loop`,
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200202 :exc:`RuntimeError` is raised if there is no running loop in
203 current thread.
204
Yury Selivanov47150392018-09-18 17:55:44 -0400205 This function has been **added in Python 3.7**. Prior to
206 Python 3.7, the low-level :func:`asyncio.ensure_future` function
207 can be used instead::
208
209 async def coro():
210 ...
211
212 # In Python 3.7+
213 task = asyncio.create_task(coro())
214 ...
215
216 # This works in all Python versions but is less readable
217 task = asyncio.ensure_future(coro())
218 ...
219
Andrew Svetlovf74ef452017-12-15 07:04:38 +0200220 .. versionadded:: 3.7
221
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300222 .. versionchanged:: 3.8
223 Added the ``name`` parameter.
224
Victor Stinnerea3183f2013-12-03 01:08:00 +0100225
Yury Selivanov3faaa882018-09-14 13:32:07 -0700226Sleeping
227========
Andrew Svetlovf1240162016-01-11 14:40:35 +0200228
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100229.. coroutinefunction:: sleep(delay, result=None, \*, loop=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100230
Yury Selivanov3faaa882018-09-14 13:32:07 -0700231 Block for *delay* seconds.
232
233 If *result* is provided, it is returned to the caller
Eli Bendersky2d26af82014-01-20 06:59:23 -0800234 when the coroutine completes.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100235
Yury Selivanov47150392018-09-18 17:55:44 -0400236 The *loop* argument is deprecated and scheduled for removal
237 in Python 4.0.
238
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700239 .. _asyncio_example_sleep:
Victor Stinner45b27ed2014-02-01 02:36:43 +0100240
Yury Selivanov3faaa882018-09-14 13:32:07 -0700241 Example of coroutine displaying the current date every second
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400242 for 5 seconds::
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100243
Yury Selivanov3faaa882018-09-14 13:32:07 -0700244 import asyncio
245 import datetime
Victor Stinnerea3183f2013-12-03 01:08:00 +0100246
Yury Selivanov3faaa882018-09-14 13:32:07 -0700247 async def display_date():
248 loop = asyncio.get_running_loop()
249 end_time = loop.time() + 5.0
250 while True:
251 print(datetime.datetime.now())
252 if (loop.time() + 1.0) >= end_time:
253 break
254 await asyncio.sleep(1)
255
256 asyncio.run(display_date())
257
258
259Running Tasks Concurrently
260==========================
261
Yury Selivanov47150392018-09-18 17:55:44 -0400262.. awaitablefunction:: gather(\*fs, loop=None, return_exceptions=False)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700263
Yury Selivanov47150392018-09-18 17:55:44 -0400264 Run :ref:`awaitable objects <asyncio-awaitables>` in the *fs*
265 sequence *concurrently*.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700266
Yury Selivanov47150392018-09-18 17:55:44 -0400267 If any awaitable in *fs* is a coroutine, it is automatically
268 scheduled as a Task.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700269
Yury Selivanov47150392018-09-18 17:55:44 -0400270 If all awaitables are completed successfully, the result is an
271 aggregate list of returned values. The order of result values
272 corresponds to the order of awaitables in *fs*.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700273
Yury Selivanov47150392018-09-18 17:55:44 -0400274 If *return_exceptions* is ``True``, exceptions are treated the
275 same as successful results, and aggregated in the result list.
276 Otherwise, the first raised exception is immediately propagated
277 to the task that awaits on ``gather()``.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700278
Yury Selivanov47150392018-09-18 17:55:44 -0400279 If ``gather`` is *cancelled*, all submitted awaitables
Yury Selivanov3faaa882018-09-14 13:32:07 -0700280 (that have not completed yet) are also *cancelled*.
281
Yury Selivanov47150392018-09-18 17:55:44 -0400282 If any Task or Future from the *fs* sequence is *cancelled*, it is
283 treated as if it raised :exc:`CancelledError` -- the ``gather()``
284 call is **not** cancelled in this case. This is to prevent the
285 cancellation of one submitted Task/Future to cause other
286 Tasks/Futures to be cancelled.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700287
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700288 .. _asyncio_example_gather:
289
Yury Selivanov3faaa882018-09-14 13:32:07 -0700290 Example::
291
292 import asyncio
293
294 async def factorial(name, number):
295 f = 1
296 for i in range(2, number + 1):
297 print(f"Task {name}: Compute factorial({i})...")
298 await asyncio.sleep(1)
299 f *= i
300 print(f"Task {name}: factorial({number}) = {f}")
301
302 async def main():
Yury Selivanov47150392018-09-18 17:55:44 -0400303 # Schedule three calls *concurrently*:
Yury Selivanov3faaa882018-09-14 13:32:07 -0700304 await asyncio.gather(
305 factorial("A", 2),
306 factorial("B", 3),
307 factorial("C", 4),
Miguel Ángel García9c53fa62018-09-18 08:01:26 +0200308 )
Yury Selivanov3faaa882018-09-14 13:32:07 -0700309
310 asyncio.run(main())
311
312 # Expected output:
313 #
314 # Task A: Compute factorial(2)...
315 # Task B: Compute factorial(2)...
316 # Task C: Compute factorial(2)...
317 # Task A: factorial(2) = 2
318 # Task B: Compute factorial(3)...
319 # Task C: Compute factorial(3)...
320 # Task B: factorial(3) = 6
321 # Task C: Compute factorial(4)...
322 # Task C: factorial(4) = 24
323
Yury Selivanov47150392018-09-18 17:55:44 -0400324 .. versionchanged:: 3.7
325 If the *gather* itself is cancelled, the cancellation is
326 propagated regardless of *return_exceptions*.
327
Yury Selivanov3faaa882018-09-14 13:32:07 -0700328
329Shielding Tasks From Cancellation
330=================================
331
Yury Selivanov47150392018-09-18 17:55:44 -0400332.. awaitablefunction:: shield(fut, \*, loop=None)
Yury Selivanov3faaa882018-09-14 13:32:07 -0700333
Yury Selivanov47150392018-09-18 17:55:44 -0400334 Protect an :ref:`awaitable object <asyncio-awaitables>`
335 from being :meth:`cancelled <Task.cancel>`.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700336
337 *fut* can be a coroutine, a Task, or a Future-like object. If
Yury Selivanov47150392018-09-18 17:55:44 -0400338 *fut* is a coroutine it is automatically scheduled as a Task.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100339
340 The statement::
341
Andrew Svetlov88743422017-12-11 17:35:49 +0200342 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100343
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400344 is equivalent to::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100345
Andrew Svetlov88743422017-12-11 17:35:49 +0200346 res = await something()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100347
Yury Selivanov3faaa882018-09-14 13:32:07 -0700348 *except* that if the coroutine containing it is cancelled, the
349 Task running in ``something()`` is not cancelled. From the point
350 of view of ``something()``, the cancellation did not happen.
351 Although its caller is still cancelled, so the "await" expression
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400352 still raises a :exc:`CancelledError`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100353
Yury Selivanov3faaa882018-09-14 13:32:07 -0700354 If ``something()`` is cancelled by other means (i.e. from within
355 itself) that would also cancel ``shield()``.
356
357 If it is desired to completely ignore cancellation (not recommended)
358 the ``shield()`` function should be combined with a try/except
359 clause, as follows::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100360
361 try:
Andrew Svetlov88743422017-12-11 17:35:49 +0200362 res = await shield(something())
Victor Stinnerea3183f2013-12-03 01:08:00 +0100363 except CancelledError:
364 res = None
365
Yury Selivanov950204d2016-05-16 16:23:00 -0400366
Yury Selivanov3faaa882018-09-14 13:32:07 -0700367Timeouts
368========
369
370.. coroutinefunction:: wait_for(fut, timeout, \*, loop=None)
371
Yury Selivanov47150392018-09-18 17:55:44 -0400372 Wait for the *fut* :ref:`awaitable <asyncio-awaitables>`
373 to complete with a timeout.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700374
Yury Selivanov47150392018-09-18 17:55:44 -0400375 If *fut* is a coroutine it is automatically scheduled as a Task.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700376
377 *timeout* can either be ``None`` or a float or int number of seconds
378 to wait for. If *timeout* is ``None``, block until the future
379 completes.
380
381 If a timeout occurs, it cancels the task and raises
382 :exc:`asyncio.TimeoutError`.
383
Yury Selivanov47150392018-09-18 17:55:44 -0400384 To avoid the task :meth:`cancellation <Task.cancel>`,
385 wrap it in :func:`shield`.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700386
387 The function will wait until the future is actually cancelled,
388 so the total wait time may exceed the *timeout*.
389
390 If the wait is cancelled, the future *fut* is also cancelled.
391
Yury Selivanov47150392018-09-18 17:55:44 -0400392 The *loop* argument is deprecated and scheduled for removal
393 in Python 4.0.
394
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700395 .. _asyncio_example_waitfor:
396
Yury Selivanov3faaa882018-09-14 13:32:07 -0700397 Example::
398
399 async def eternity():
400 # Sleep for one hour
401 await asyncio.sleep(3600)
402 print('yay!')
403
404 async def main():
405 # Wait for at most 1 second
406 try:
407 await asyncio.wait_for(eternity(), timeout=1.0)
408 except asyncio.TimeoutError:
409 print('timeout!')
410
411 asyncio.run(main())
412
413 # Expected output:
414 #
415 # timeout!
416
417 .. versionchanged:: 3.7
418 When *fut* is cancelled due to a timeout, ``wait_for`` waits
419 for *fut* to be cancelled. Previously, it raised
420 :exc:`asyncio.TimeoutError` immediately.
421
422
423Waiting Primitives
424==================
425
426.. coroutinefunction:: wait(fs, \*, loop=None, timeout=None,\
Andrew Svetlovf1240162016-01-11 14:40:35 +0200427 return_when=ALL_COMPLETED)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100428
Yury Selivanov47150392018-09-18 17:55:44 -0400429 Run :ref:`awaitable objects <asyncio-awaitables>` in the *fs*
430 sequence concurrently and block until the condition specified
431 by *return_when*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100432
Yury Selivanov47150392018-09-18 17:55:44 -0400433 If any awaitable in *fs* is a coroutine, it is automatically
434 scheduled as a Task.
Victor Stinnerdb74d982014-06-10 11:16:05 +0200435
Yury Selivanov3faaa882018-09-14 13:32:07 -0700436 Returns two sets of Tasks/Futures: ``(done, pending)``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100437
Yury Selivanov47150392018-09-18 17:55:44 -0400438 The *loop* argument is deprecated and scheduled for removal
439 in Python 4.0.
440
Yury Selivanov3faaa882018-09-14 13:32:07 -0700441 *timeout* (a float or int), if specified, can be used to control
442 the maximum number of seconds to wait before returning.
443
444 Note that this function does not raise :exc:`asyncio.TimeoutError`.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400445 Futures or Tasks that aren't done when the timeout occurs are simply
Yury Selivanov3faaa882018-09-14 13:32:07 -0700446 returned in the second set.
447
448 *return_when* indicates when this function should return. It must
449 be one of the following constants:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100450
451 .. tabularcolumns:: |l|L|
452
453 +-----------------------------+----------------------------------------+
454 | Constant | Description |
455 +=============================+========================================+
456 | :const:`FIRST_COMPLETED` | The function will return when any |
457 | | future finishes or is cancelled. |
458 +-----------------------------+----------------------------------------+
459 | :const:`FIRST_EXCEPTION` | The function will return when any |
460 | | future finishes by raising an |
461 | | exception. If no future raises an |
462 | | exception then it is equivalent to |
463 | | :const:`ALL_COMPLETED`. |
464 +-----------------------------+----------------------------------------+
465 | :const:`ALL_COMPLETED` | The function will return when all |
466 | | futures finish or are cancelled. |
467 +-----------------------------+----------------------------------------+
468
Yury Selivanov3faaa882018-09-14 13:32:07 -0700469 Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the
470 futures when a timeout occurs.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100471
472 Usage::
473
Andrew Svetlov88743422017-12-11 17:35:49 +0200474 done, pending = await asyncio.wait(fs)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100475
Victor Stinnerea3183f2013-12-03 01:08:00 +0100476
Yury Selivanov3faaa882018-09-14 13:32:07 -0700477.. function:: as_completed(fs, \*, loop=None, timeout=None)
478
Yury Selivanov47150392018-09-18 17:55:44 -0400479 Run :ref:`awaitable objects <asyncio-awaitables>` in the *fs*
480 set concurrently. Return an iterator of :class:`Future` objects.
481 Each Future object returned represents the earliest result
482 from the set of the remaining awaitables.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700483
484 Raises :exc:`asyncio.TimeoutError` if the timeout occurs before
485 all Futures are done.
486
487 Example::
488
489 for f in as_completed(fs):
Yury Selivanov47150392018-09-18 17:55:44 -0400490 earliest_result = await f
Yury Selivanov3faaa882018-09-14 13:32:07 -0700491 # ...
Victor Stinnerea3183f2013-12-03 01:08:00 +0100492
Victor Stinner3e09e322013-12-03 01:22:06 +0100493
Yury Selivanov3faaa882018-09-14 13:32:07 -0700494Scheduling From Other Threads
495=============================
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100496
Yury Selivanov3faaa882018-09-14 13:32:07 -0700497.. function:: run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100498
Yury Selivanov3faaa882018-09-14 13:32:07 -0700499 Submit a coroutine to the given event loop. Thread-safe.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100500
Yury Selivanov47150392018-09-18 17:55:44 -0400501 Return a :class:`concurrent.futures.Future` to wait for the result
502 from another OS thread.
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100503
Yury Selivanov3faaa882018-09-14 13:32:07 -0700504 This function is meant to be called from a different OS thread
505 than the one where the event loop is running. Example::
Victor Stinner72dcb0a2015-04-03 17:08:19 +0200506
Yury Selivanov3faaa882018-09-14 13:32:07 -0700507 # Create a coroutine
508 coro = asyncio.sleep(1, result=3)
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500509
Yury Selivanov3faaa882018-09-14 13:32:07 -0700510 # Submit the coroutine to a given loop
511 future = asyncio.run_coroutine_threadsafe(coro, loop)
Victor Stinner1ad5afc2014-01-30 00:18:50 +0100512
Yury Selivanov3faaa882018-09-14 13:32:07 -0700513 # Wait for the result with an optional timeout argument
514 assert future.result(timeout) == 3
515
516 If an exception is raised in the coroutine, the returned Future
517 will be notified. It can also be used to cancel the task in
518 the event loop::
519
520 try:
521 result = future.result(timeout)
522 except asyncio.TimeoutError:
523 print('The coroutine took too long, cancelling the task...')
524 future.cancel()
525 except Exception as exc:
526 print('The coroutine raised an exception: {!r}'.format(exc))
527 else:
528 print('The coroutine returned: {!r}'.format(result))
529
530 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
531 section of the documentation.
532
533 Unlike other asyncio functions this functions requires the *loop*
534 argument to be passed explicitly.
535
536 .. versionadded:: 3.5.1
537
538
539Introspection
540=============
541
542
543.. function:: current_task(loop=None)
544
545 Return the currently running :class:`Task` instance, or ``None`` if
546 no task is running.
547
548 If *loop* is ``None`` :func:`get_running_loop` is used to get
549 the current loop.
550
551 .. versionadded:: 3.7
552
553
554.. function:: all_tasks(loop=None)
555
556 Return a set of not yet finished :class:`Task` objects run by
557 the loop.
558
559 If *loop* is ``None``, :func:`get_running_loop` is used for getting
560 current loop.
561
562 .. versionadded:: 3.7
563
564
565Task Object
566===========
567
568.. class:: Task(coro, \*, loop=None, name=None)
569
570 A :class:`Future`-like object that wraps a Python
571 :ref:`coroutine <coroutine>`. Not thread-safe.
572
573 Tasks are used to run coroutines in event loops.
574 If a coroutine awaits on a Future, the Task suspends
575 the execution of the coroutine and waits for the completion
576 of the Future. When the Future is *done*, the execution of
577 the wrapped coroutine resumes.
578
579 Event loops use cooperative scheduling: an event loop runs
580 one Task at a time. While a Task awaits for the completion of a
581 Future, the event loop runs other Tasks, callbacks, or performs
582 IO operations.
583
584 Use the high-level :func:`asyncio.create_task` function to create
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400585 Tasks, or the low-level :meth:`loop.create_task` or
586 :func:`ensure_future` functions. Manual instantiation of Tasks
587 is discouraged.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700588
589 To cancel a running Task use the :meth:`cancel` method. Calling it
590 will cause the Task to throw a :exc:`CancelledError` exception into
591 the wrapped coroutine. If a coroutine is awaiting on a Future
592 object during cancellation, the Future object will be cancelled.
593
594 :meth:`cancelled` can be used to check if the Task was cancelled.
595 The method returns ``True`` if the wrapped coroutine did not
596 suppress the :exc:`CancelledError` exception and was actually
597 cancelled.
598
599 :class:`asyncio.Task` inherits from :class:`Future` all of its
600 APIs except :meth:`Future.set_result` and
601 :meth:`Future.set_exception`.
602
603 Tasks support the :mod:`contextvars` module. When a Task
604 is created it copies the current context and later runs its
605 coroutine in the copied context.
Elvis Pranskevichuse2b340a2018-05-29 17:31:01 -0400606
607 .. versionchanged:: 3.7
Yury Selivanov3faaa882018-09-14 13:32:07 -0700608 Added support for the :mod:`contextvars` module.
609
610 .. versionchanged:: 3.8
611 Added the ``name`` parameter.
612
613 .. method:: cancel()
614
615 Request the Task to be cancelled.
616
617 This arranges for a :exc:`CancelledError` exception to be thrown
618 into the wrapped coroutine on the next cycle of the event loop.
619
620 The coroutine then has a chance to clean up or even deny the
621 request by suppressing the exception with a :keyword:`try` ...
622 ... ``except CancelledError`` ... :keyword:`finally` block.
623 Therefore, unlike :meth:`Future.cancel`, :meth:`Task.cancel` does
624 not guarantee that the Task will be cancelled, although
625 suppressing cancellation completely is not common and is actively
626 discouraged.
627
Yury Selivanov7372c3b2018-09-14 15:11:24 -0700628 .. _asyncio_example_task_cancel:
629
Yury Selivanov3faaa882018-09-14 13:32:07 -0700630 The following example illustrates how coroutines can intercept
631 the cancellation request::
632
633 async def cancel_me():
634 print('cancel_me(): before sleep')
635
636 try:
637 # Wait for 1 hour
638 await asyncio.sleep(3600)
639 except asyncio.CancelledError:
640 print('cancel_me(): cancel sleep')
641 raise
642 finally:
643 print('cancel_me(): after sleep')
644
645 async def main():
646 # Create a "cancel_me" Task
647 task = asyncio.create_task(cancel_me())
648
649 # Wait for 1 second
650 await asyncio.sleep(1)
651
652 task.cancel()
653 try:
654 await task
655 except asyncio.CancelledError:
656 print("main(): cancel_me is cancelled now")
657
658 asyncio.run(main())
659
660 # Expected output:
661 #
662 # cancel_me(): before sleep
663 # cancel_me(): cancel sleep
664 # cancel_me(): after sleep
665 # main(): cancel_me is cancelled now
666
667 .. method:: cancelled()
668
669 Return ``True`` if the Task is *cancelled*.
670
671 The Task is *cancelled* when the cancellation was requested with
672 :meth:`cancel` and the wrapped coroutine propagated the
673 :exc:`CancelledError` exception thrown into it.
674
675 .. method:: done()
676
677 Return ``True`` if the Task is *done*.
678
679 A Task is *done* when the wrapped coroutine either returned
680 a value, raised an exception, or the Task was cancelled.
681
682 .. method:: get_stack(\*, limit=None)
683
684 Return the list of stack frames for this Task.
685
686 If the wrapped coroutine is not done, this returns the stack
687 where it is suspended. If the coroutine has completed
688 successfully or was cancelled, this returns an empty list.
689 If the coroutine was terminated by an exception, this returns
690 the list of traceback frames.
691
692 The frames are always ordered from oldest to newest.
693
694 Only one stack frame is returned for a suspended coroutine.
695
696 The optional *limit* argument sets the maximum number of frames
697 to return; by default all available frames are returned.
698 The ordering of the returned list differs depending on whether
699 a stack or a traceback is returned: the newest frames of a
700 stack are returned, but the oldest frames of a traceback are
701 returned. (This matches the behavior of the traceback module.)
702
703 .. method:: print_stack(\*, limit=None, file=None)
704
705 Print the stack or traceback for this Task.
706
707 This produces output similar to that of the traceback module
708 for the frames retrieved by :meth:`get_stack`.
709
710 The *limit* argument is passed to :meth:`get_stack` directly.
711
712 The *file* argument is an I/O stream to which the output
713 is written; by default output is written to :data:`sys.stderr`.
714
715 .. method:: get_name()
716
717 Return the name of the Task.
718
719 If no name has been explicitly assigned to the Task, the default
720 asyncio Task implementation generates a default name during
721 instantiation.
722
723 .. versionadded:: 3.8
724
725 .. method:: set_name(value)
726
727 Set the name of the Task.
728
729 The *value* argument can be any object, which is then
730 converted to a string.
731
732 In the default Task implementation, the name will be visible
733 in the :func:`repr` output of a task object.
734
735 .. versionadded:: 3.8
736
737 .. classmethod:: all_tasks(loop=None)
738
739 Return a set of all tasks for an event loop.
740
741 By default all tasks for the current event loop are returned.
742 If *loop* is ``None``, the :func:`get_event_loop` function
743 is used to get the current loop.
744
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400745 This method is **deprecated** and will be removed in
Yury Selivanov3faaa882018-09-14 13:32:07 -0700746 Python 3.9. Use the :func:`all_tasks` function instead.
747
748 .. classmethod:: current_task(loop=None)
749
750 Return the currently running task or ``None``.
751
752 If *loop* is ``None``, the :func:`get_event_loop` function
753 is used to get the current loop.
754
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400755 This method is **deprecated** and will be removed in
Yury Selivanov3faaa882018-09-14 13:32:07 -0700756 Python 3.9. Use the :func:`current_task` function instead.
757
758
759.. _asyncio_generator_based_coro:
760
761Generator-based Coroutines
762==========================
763
764.. note::
765
766 Support for generator-based coroutines is **deprecated** and
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400767 is scheduled for removal in Python 4.0.
Yury Selivanov3faaa882018-09-14 13:32:07 -0700768
769Generator-based coroutines predate async/await syntax. They are
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400770Python generators that use ``yield from`` expressions to await
Yury Selivanov3faaa882018-09-14 13:32:07 -0700771on Futures and other coroutines.
772
773Generator-based coroutines should be decorated with
774:func:`@asyncio.coroutine <asyncio.coroutine>`, although this is not
775enforced.
776
777
778.. decorator:: coroutine
779
780 Decorator to mark generator-based coroutines.
781
782 This decorator enables legacy generator-based coroutines to be
783 compatible with async/await code::
784
785 @asyncio.coroutine
786 def old_style_coroutine():
787 yield from asyncio.sleep(1)
788
789 async def main():
790 await old_style_coroutine()
791
792 This decorator is **deprecated** and is scheduled for removal in
793 Python 4.0.
794
795 This decorator should not be used for :keyword:`async def`
796 coroutines.
797
798.. function:: iscoroutine(obj)
799
800 Return ``True`` if *obj* is a :ref:`coroutine object <coroutine>`.
801
802 This method is different from :func:`inspect.iscoroutine` because
803 it returns ``True`` for generator-based coroutines decorated with
804 :func:`@coroutine <coroutine>`.
805
806.. function:: iscoroutinefunction(func)
807
808 Return ``True`` if *func* is a :ref:`coroutine function
809 <coroutine>`.
810
811 This method is different from :func:`inspect.iscoroutinefunction`
812 because it returns ``True`` for generator-based coroutine functions
813 decorated with :func:`@coroutine <coroutine>`.