summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/library%2Fasyncio-task.html
blob: 3c0257625d1337e5ad63c6456ea80e2ced737867 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
 <h1>Coroutines and Tasks</h1> <p>This section outlines high-level asyncio APIs to work with coroutines and Tasks.</p>  <ul class="simple"> <li><a class="reference internal" href="#coroutines" id="id2">Coroutines</a></li> <li><a class="reference internal" href="#awaitables" id="id3">Awaitables</a></li> <li><a class="reference internal" href="#creating-tasks" id="id4">Creating Tasks</a></li> <li><a class="reference internal" href="#task-cancellation" id="id5">Task Cancellation</a></li> <li><a class="reference internal" href="#task-groups" id="id6">Task Groups</a></li> <li><a class="reference internal" href="#sleeping" id="id7">Sleeping</a></li> <li><a class="reference internal" href="#running-tasks-concurrently" id="id8">Running Tasks Concurrently</a></li> <li><a class="reference internal" href="#eager-task-factory" id="id9">Eager Task Factory</a></li> <li><a class="reference internal" href="#shielding-from-cancellation" id="id10">Shielding From Cancellation</a></li> <li><a class="reference internal" href="#timeouts" id="id11">Timeouts</a></li> <li><a class="reference internal" href="#waiting-primitives" id="id12">Waiting Primitives</a></li> <li><a class="reference internal" href="#running-in-threads" id="id13">Running in Threads</a></li> <li><a class="reference internal" href="#scheduling-from-other-threads" id="id14">Scheduling From Other Threads</a></li> <li><a class="reference internal" href="#introspection" id="id15">Introspection</a></li> <li><a class="reference internal" href="#task-object" id="id16">Task Object</a></li> </ul>  <section id="coroutines"> <span id="coroutine"></span><h2>Coroutines</h2> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/asyncio/coroutines.py">Lib/asyncio/coroutines.py</a></p>  <p><a class="reference internal" href="../glossary#term-coroutine"><span class="xref std std-term">Coroutines</span></a> declared with the async/await syntax is the preferred way of writing asyncio applications. For example, the following snippet of code prints “hello”, waits 1 second, and then prints “world”:</p> <pre data-language="python">&gt;&gt;&gt; import asyncio

&gt;&gt;&gt; async def main():
...     print('hello')
...     await asyncio.sleep(1)
...     print('world')

&gt;&gt;&gt; asyncio.run(main())
hello
world
</pre> <p>Note that simply calling a coroutine will not schedule it to be executed:</p> <pre data-language="python">&gt;&gt;&gt; main()
&lt;coroutine object main at 0x1053bb7c8&gt;
</pre> <p>To actually run a coroutine, asyncio provides the following mechanisms:</p> <ul> <li>The <a class="reference internal" href="asyncio-runner#asyncio.run" title="asyncio.run"><code>asyncio.run()</code></a> function to run the top-level entry point “main()” function (see the above example.)</li> <li>
<p>Awaiting on a coroutine. The following snippet of code will print “hello” after waiting for 1 second, and then print “world” after waiting for <em>another</em> 2 seconds:</p> <pre data-language="python">import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print(f"started at {time.strftime('%X')}")

    await say_after(1, 'hello')
    await say_after(2, 'world')

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())
</pre> <p>Expected output:</p> <pre data-language="python">started at 17:13:52
hello
world
finished at 17:13:55
</pre> </li> <li>
<p>The <a class="reference internal" href="#asyncio.create_task" title="asyncio.create_task"><code>asyncio.create_task()</code></a> function to run coroutines concurrently as asyncio <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code>Tasks</code></a>.</p> <p>Let’s modify the above example and run two <code>say_after</code> coroutines <em>concurrently</em>:</p> <pre data-language="python">async def main():
    task1 = asyncio.create_task(
        say_after(1, 'hello'))

    task2 = asyncio.create_task(
        say_after(2, 'world'))

    print(f"started at {time.strftime('%X')}")

    # Wait until both tasks are completed (should take
    # around 2 seconds.)
    await task1
    await task2

    print(f"finished at {time.strftime('%X')}")
</pre> <p>Note that expected output now shows that the snippet runs 1 second faster than before:</p> <pre data-language="python">started at 17:14:32
hello
world
finished at 17:14:34
</pre> </li> <li>
<p>The <a class="reference internal" href="#asyncio.TaskGroup" title="asyncio.TaskGroup"><code>asyncio.TaskGroup</code></a> class provides a more modern alternative to <a class="reference internal" href="#asyncio.create_task" title="asyncio.create_task"><code>create_task()</code></a>. Using this API, the last example becomes:</p> <pre data-language="python">async def main():
    async with asyncio.TaskGroup() as tg:
        task1 = tg.create_task(
            say_after(1, 'hello'))

        task2 = tg.create_task(
            say_after(2, 'world'))

        print(f"started at {time.strftime('%X')}")

    # The await is implicit when the context manager exits.

    print(f"finished at {time.strftime('%X')}")
</pre> <p>The timing and output should be the same as for the previous version.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11: </span><a class="reference internal" href="#asyncio.TaskGroup" title="asyncio.TaskGroup"><code>asyncio.TaskGroup</code></a>.</p> </div> </li> </ul> </section> <section id="awaitables"> <span id="asyncio-awaitables"></span><h2>Awaitables</h2> <p>We say that an object is an <strong>awaitable</strong> object if it can be used in an <a class="reference internal" href="../reference/expressions#await"><code>await</code></a> expression. Many asyncio APIs are designed to accept awaitables.</p> <p>There are three main types of <em>awaitable</em> objects: <strong>coroutines</strong>, <strong>Tasks</strong>, and <strong>Futures</strong>.</p> <h4 class="rubric">Coroutines</h4> <p>Python coroutines are <em>awaitables</em> and therefore can be awaited from other coroutines:</p> <pre data-language="python">import asyncio

async def nested():
    return 42

async def main():
    # Nothing happens if we just call "nested()".
    # A coroutine object is created but not awaited,
    # so it *won't run at all*.
    nested()

    # Let's do it differently now and await it:
    print(await nested())  # will print "42".

asyncio.run(main())
</pre> <div class="admonition important"> <p class="admonition-title">Important</p> <p>In this documentation the term “coroutine” can be used for two closely related concepts:</p> <ul class="simple"> <li>a <em>coroutine function</em>: an <a class="reference internal" href="../reference/compound_stmts#async-def"><code>async def</code></a> function;</li> <li>a <em>coroutine object</em>: an object returned by calling a <em>coroutine function</em>.</li> </ul> </div> <h4 class="rubric">Tasks</h4> <p><em>Tasks</em> are used to schedule coroutines <em>concurrently</em>.</p> <p>When a coroutine is wrapped into a <em>Task</em> with functions like <a class="reference internal" href="#asyncio.create_task" title="asyncio.create_task"><code>asyncio.create_task()</code></a> the coroutine is automatically scheduled to run soon:</p> <pre data-language="python">import asyncio

async def nested():
    return 42

async def main():
    # Schedule nested() to run soon concurrently
    # with "main()".
    task = asyncio.create_task(nested())

    # "task" can now be used to cancel "nested()", or
    # can simply be awaited to wait until it is complete:
    await task

asyncio.run(main())
</pre> <h4 class="rubric">Futures</h4> <p>A <a class="reference internal" href="asyncio-future#asyncio.Future" title="asyncio.Future"><code>Future</code></a> is a special <strong>low-level</strong> awaitable object that represents an <strong>eventual result</strong> of an asynchronous operation.</p> <p>When a Future object is <em>awaited</em> it means that the coroutine will wait until the Future is resolved in some other place.</p> <p>Future objects in asyncio are needed to allow callback-based code to be used with async/await.</p> <p>Normally <strong>there is no need</strong> to create Future objects at the application level code.</p> <p>Future objects, sometimes exposed by libraries and some asyncio APIs, can be awaited:</p> <pre data-language="python">async def main():
    await function_that_returns_a_future_object()

    # this is also valid:
    await asyncio.gather(
        function_that_returns_a_future_object(),
        some_python_coroutine()
    )
</pre> <p>A good example of a low-level function that returns a Future object is <a class="reference internal" href="asyncio-eventloop#asyncio.loop.run_in_executor" title="asyncio.loop.run_in_executor"><code>loop.run_in_executor()</code></a>.</p> </section> <section id="creating-tasks"> <h2>Creating Tasks</h2> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/asyncio/tasks.py">Lib/asyncio/tasks.py</a></p>  <dl class="py function"> <dt class="sig sig-object py" id="asyncio.create_task">
<code>asyncio.create_task(coro, *, name=None, context=None)</code> </dt> <dd>
<p>Wrap the <em>coro</em> <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine</span></a> into a <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code>Task</code></a> and schedule its execution. Return the Task object.</p> <p>If <em>name</em> is not <code>None</code>, it is set as the name of the task using <a class="reference internal" href="#asyncio.Task.set_name" title="asyncio.Task.set_name"><code>Task.set_name()</code></a>.</p> <p>An optional keyword-only <em>context</em> argument allows specifying a custom <a class="reference internal" href="contextvars#contextvars.Context" title="contextvars.Context"><code>contextvars.Context</code></a> for the <em>coro</em> to run in. The current context copy is created when no <em>context</em> is provided.</p> <p>The task is executed in the loop returned by <a class="reference internal" href="asyncio-eventloop#asyncio.get_running_loop" title="asyncio.get_running_loop"><code>get_running_loop()</code></a>, <a class="reference internal" href="exceptions#RuntimeError" title="RuntimeError"><code>RuntimeError</code></a> is raised if there is no running loop in current thread.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p><a class="reference internal" href="#asyncio.TaskGroup.create_task" title="asyncio.TaskGroup.create_task"><code>asyncio.TaskGroup.create_task()</code></a> is a new alternative leveraging structural concurrency; it allows for waiting for a group of related tasks with strong safety guarantees.</p> </div> <div class="admonition important"> <p class="admonition-title">Important</p> <p>Save a reference to the result of this function, to avoid a task disappearing mid-execution. The event loop only keeps weak references to tasks. A task that isn’t referenced elsewhere may get garbage collected at any time, even before it’s done. For reliable “fire-and-forget” background tasks, gather them in a collection:</p> <pre data-language="python">background_tasks = set()

for i in range(10):
    task = asyncio.create_task(some_coro(param=i))

    # Add task to the set. This creates a strong reference.
    background_tasks.add(task)

    # To prevent keeping references to finished tasks forever,
    # make each task remove its own reference from the set after
    # completion:
    task.add_done_callback(background_tasks.discard)
</pre> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>Added the <em>name</em> parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>context</em> parameter.</p> </div> </dd>
</dl> </section> <section id="task-cancellation"> <h2>Task Cancellation</h2> <p>Tasks can easily and safely be cancelled. When a task is cancelled, <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>asyncio.CancelledError</code></a> will be raised in the task at the next opportunity.</p> <p>It is recommended that coroutines use <code>try/finally</code> blocks to robustly perform clean-up logic. In case <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>asyncio.CancelledError</code></a> is explicitly caught, it should generally be propagated when clean-up is complete. <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>asyncio.CancelledError</code></a> directly subclasses <a class="reference internal" href="exceptions#BaseException" title="BaseException"><code>BaseException</code></a> so most code will not need to be aware of it.</p> <p>The asyncio components that enable structured concurrency, like <a class="reference internal" href="#asyncio.TaskGroup" title="asyncio.TaskGroup"><code>asyncio.TaskGroup</code></a> and <a class="reference internal" href="#asyncio.timeout" title="asyncio.timeout"><code>asyncio.timeout()</code></a>, are implemented using cancellation internally and might misbehave if a coroutine swallows <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>asyncio.CancelledError</code></a>. Similarly, user code should not generally call <a class="reference internal" href="#asyncio.Task.uncancel" title="asyncio.Task.uncancel"><code>uncancel</code></a>. However, in cases when suppressing <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>asyncio.CancelledError</code></a> is truly desired, it is necessary to also call <code>uncancel()</code> to completely remove the cancellation state.</p> </section> <section id="task-groups"> <span id="taskgroups"></span><h2>Task Groups</h2> <p>Task groups combine a task creation API with a convenient and reliable way to wait for all tasks in the group to finish.</p> <dl class="py class"> <dt class="sig sig-object py" id="asyncio.TaskGroup">
<code>class asyncio.TaskGroup</code> </dt> <dd>
<p>An <a class="reference internal" href="../reference/datamodel#async-context-managers"><span class="std std-ref">asynchronous context manager</span></a> holding a group of tasks. Tasks can be added to the group using <a class="reference internal" href="#asyncio.create_task" title="asyncio.create_task"><code>create_task()</code></a>. All tasks are awaited when the context manager exits.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.TaskGroup.create_task">
<code>create_task(coro, *, name=None, context=None)</code> </dt> <dd>
<p>Create a task in this task group. The signature matches that of <a class="reference internal" href="#asyncio.create_task" title="asyncio.create_task"><code>asyncio.create_task()</code></a>.</p> </dd>
</dl> </dd>
</dl> <p>Example:</p> <pre data-language="python">async def main():
    async with asyncio.TaskGroup() as tg:
        task1 = tg.create_task(some_coro(...))
        task2 = tg.create_task(another_coro(...))
    print(f"Both tasks have completed now: {task1.result()}, {task2.result()}")
</pre> <p>The <code>async with</code> statement will wait for all tasks in the group to finish. While waiting, new tasks may still be added to the group (for example, by passing <code>tg</code> into one of the coroutines and calling <code>tg.create_task()</code> in that coroutine). Once the last task has finished and the <code>async with</code> block is exited, no new tasks may be added to the group.</p> <p>The first time any of the tasks belonging to the group fails with an exception other than <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>asyncio.CancelledError</code></a>, the remaining tasks in the group are cancelled. No further tasks can then be added to the group. At this point, if the body of the <code>async with</code> statement is still active (i.e., <a class="reference internal" href="../reference/datamodel#object.__aexit__" title="object.__aexit__"><code>__aexit__()</code></a> hasn’t been called yet), the task directly containing the <code>async with</code> statement is also cancelled. The resulting <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>asyncio.CancelledError</code></a> will interrupt an <code>await</code>, but it will not bubble out of the containing <code>async with</code> statement.</p> <p>Once all tasks have finished, if any tasks have failed with an exception other than <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>asyncio.CancelledError</code></a>, those exceptions are combined in an <a class="reference internal" href="exceptions#ExceptionGroup" title="ExceptionGroup"><code>ExceptionGroup</code></a> or <a class="reference internal" href="exceptions#BaseExceptionGroup" title="BaseExceptionGroup"><code>BaseExceptionGroup</code></a> (as appropriate; see their documentation) which is then raised.</p> <p>Two base exceptions are treated specially: If any task fails with <a class="reference internal" href="exceptions#KeyboardInterrupt" title="KeyboardInterrupt"><code>KeyboardInterrupt</code></a> or <a class="reference internal" href="exceptions#SystemExit" title="SystemExit"><code>SystemExit</code></a>, the task group still cancels the remaining tasks and waits for them, but then the initial <a class="reference internal" href="exceptions#KeyboardInterrupt" title="KeyboardInterrupt"><code>KeyboardInterrupt</code></a> or <a class="reference internal" href="exceptions#SystemExit" title="SystemExit"><code>SystemExit</code></a> is re-raised instead of <a class="reference internal" href="exceptions#ExceptionGroup" title="ExceptionGroup"><code>ExceptionGroup</code></a> or <a class="reference internal" href="exceptions#BaseExceptionGroup" title="BaseExceptionGroup"><code>BaseExceptionGroup</code></a>.</p> <p>If the body of the <code>async with</code> statement exits with an exception (so <a class="reference internal" href="../reference/datamodel#object.__aexit__" title="object.__aexit__"><code>__aexit__()</code></a> is called with an exception set), this is treated the same as if one of the tasks failed: the remaining tasks are cancelled and then waited for, and non-cancellation exceptions are grouped into an exception group and raised. The exception passed into <a class="reference internal" href="../reference/datamodel#object.__aexit__" title="object.__aexit__"><code>__aexit__()</code></a>, unless it is <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>asyncio.CancelledError</code></a>, is also included in the exception group. The same special case is made for <a class="reference internal" href="exceptions#KeyboardInterrupt" title="KeyboardInterrupt"><code>KeyboardInterrupt</code></a> and <a class="reference internal" href="exceptions#SystemExit" title="SystemExit"><code>SystemExit</code></a> as in the previous paragraph.</p> </section> <section id="sleeping"> <h2>Sleeping</h2> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.sleep">
<code>coroutine asyncio.sleep(delay, result=None)</code> </dt> <dd>
<p>Block for <em>delay</em> seconds.</p> <p>If <em>result</em> is provided, it is returned to the caller when the coroutine completes.</p> <p><code>sleep()</code> always suspends the current task, allowing other tasks to run.</p> <p>Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.</p> <p id="asyncio-example-sleep">Example of coroutine displaying the current date every second for 5 seconds:</p> <pre data-language="python">import asyncio
import datetime

async def display_date():
    loop = asyncio.get_running_loop()
    end_time = loop.time() + 5.0
    while True:
        print(datetime.datetime.now())
        if (loop.time() + 1.0) &gt;= end_time:
            break
        await asyncio.sleep(1)

asyncio.run(display_date())
</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p> </div> </dd>
</dl> </section> <section id="running-tasks-concurrently"> <h2>Running Tasks Concurrently</h2> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.gather">
<code>awaitable asyncio.gather(*aws, return_exceptions=False)</code> </dt> <dd>
<p>Run <a class="reference internal" href="#asyncio-awaitables"><span class="std std-ref">awaitable objects</span></a> in the <em>aws</em> sequence <em>concurrently</em>.</p> <p>If any awaitable in <em>aws</em> is a coroutine, it is automatically scheduled as a Task.</p> <p>If all awaitables are completed successfully, the result is an aggregate list of returned values. The order of result values corresponds to the order of awaitables in <em>aws</em>.</p> <p>If <em>return_exceptions</em> is <code>False</code> (default), the first raised exception is immediately propagated to the task that awaits on <code>gather()</code>. Other awaitables in the <em>aws</em> sequence <strong>won’t be cancelled</strong> and will continue to run.</p> <p>If <em>return_exceptions</em> is <code>True</code>, exceptions are treated the same as successful results, and aggregated in the result list.</p> <p>If <code>gather()</code> is <em>cancelled</em>, all submitted awaitables (that have not completed yet) are also <em>cancelled</em>.</p> <p>If any Task or Future from the <em>aws</em> sequence is <em>cancelled</em>, it is treated as if it raised <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>CancelledError</code></a> – the <code>gather()</code> call is <strong>not</strong> cancelled in this case. This is to prevent the cancellation of one submitted Task/Future to cause other Tasks/Futures to be cancelled.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>A new alternative to create and run tasks concurrently and wait for their completion is <a class="reference internal" href="#asyncio.TaskGroup" title="asyncio.TaskGroup"><code>asyncio.TaskGroup</code></a>. <em>TaskGroup</em> provides stronger safety guarantees than <em>gather</em> for scheduling a nesting of subtasks: if a task (or a subtask, a task scheduled by a task) raises an exception, <em>TaskGroup</em> will, while <em>gather</em> will not, cancel the remaining scheduled tasks).</p> </div> <p id="asyncio-example-gather">Example:</p> <pre data-language="python">import asyncio

async def factorial(name, number):
    f = 1
    for i in range(2, number + 1):
        print(f"Task {name}: Compute factorial({number}), currently i={i}...")
        await asyncio.sleep(1)
        f *= i
    print(f"Task {name}: factorial({number}) = {f}")
    return f

async def main():
    # Schedule three calls *concurrently*:
    L = await asyncio.gather(
        factorial("A", 2),
        factorial("B", 3),
        factorial("C", 4),
    )
    print(L)

asyncio.run(main())

# Expected output:
#
#     Task A: Compute factorial(2), currently i=2...
#     Task B: Compute factorial(3), currently i=2...
#     Task C: Compute factorial(4), currently i=2...
#     Task A: factorial(2) = 2
#     Task B: Compute factorial(3), currently i=3...
#     Task C: Compute factorial(4), currently i=3...
#     Task B: factorial(3) = 6
#     Task C: Compute factorial(4), currently i=4...
#     Task C: factorial(4) = 24
#     [2, 6, 24]
</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>If <em>return_exceptions</em> is False, cancelling gather() after it has been marked done won’t cancel any submitted awaitables. For instance, gather can be marked done after propagating an exception to the caller, therefore, calling <code>gather.cancel()</code> after catching an exception (raised by one of the awaitables) from gather won’t cancel any other awaitables.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>If the <em>gather</em> itself is cancelled, the cancellation is propagated regardless of <em>return_exceptions</em>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.10: </span>Deprecation warning is emitted if no positional arguments are provided or not all positional arguments are Future-like objects and there is no running event loop.</p> </div> </dd>
</dl> </section> <section id="eager-task-factory"> <span id="id1"></span><h2>Eager Task Factory</h2> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.eager_task_factory">
<code>asyncio.eager_task_factory(loop, coro, *, name=None, context=None)</code> </dt> <dd>
<p>A task factory for eager task execution.</p> <p>When using this factory (via <a class="reference internal" href="asyncio-eventloop#asyncio.loop.set_task_factory" title="asyncio.loop.set_task_factory"><code>loop.set_task_factory(asyncio.eager_task_factory)</code></a>), coroutines begin execution synchronously during <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code>Task</code></a> construction. Tasks are only scheduled on the event loop if they block. This can be a performance improvement as the overhead of loop scheduling is avoided for coroutines that complete synchronously.</p> <p>A common example where this is beneficial is coroutines which employ caching or memoization to avoid actual I/O when possible.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Immediate execution of the coroutine is a semantic change. If the coroutine returns or raises, the task is never scheduled to the event loop. If the coroutine execution blocks, the task is scheduled to the event loop. This change may introduce behavior changes to existing applications. For example, the application’s task execution order is likely to change.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.create_eager_task_factory">
<code>asyncio.create_eager_task_factory(custom_task_constructor)</code> </dt> <dd>
<p>Create an eager task factory, similar to <a class="reference internal" href="#asyncio.eager_task_factory" title="asyncio.eager_task_factory"><code>eager_task_factory()</code></a>, using the provided <em>custom_task_constructor</em> when creating a new task instead of the default <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code>Task</code></a>.</p> <p><em>custom_task_constructor</em> must be a <em>callable</em> with the signature matching the signature of <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code>Task.__init__</code></a>. The callable must return a <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code>asyncio.Task</code></a>-compatible object.</p> <p>This function returns a <em>callable</em> intended to be used as a task factory of an event loop via <a class="reference internal" href="asyncio-eventloop#asyncio.loop.set_task_factory" title="asyncio.loop.set_task_factory"><code>loop.set_task_factory(factory)</code></a>).</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd>
</dl> </section> <section id="shielding-from-cancellation"> <h2>Shielding From Cancellation</h2> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.shield">
<code>awaitable asyncio.shield(aw)</code> </dt> <dd>
<p>Protect an <a class="reference internal" href="#asyncio-awaitables"><span class="std std-ref">awaitable object</span></a> from being <a class="reference internal" href="#asyncio.Task.cancel" title="asyncio.Task.cancel"><code>cancelled</code></a>.</p> <p>If <em>aw</em> is a coroutine it is automatically scheduled as a Task.</p> <p>The statement:</p> <pre data-language="python">task = asyncio.create_task(something())
res = await shield(task)
</pre> <p>is equivalent to:</p> <pre data-language="python">res = await something()
</pre> <p><em>except</em> that if the coroutine containing it is cancelled, the Task running in <code>something()</code> is not cancelled. From the point of view of <code>something()</code>, the cancellation did not happen. Although its caller is still cancelled, so the “await” expression still raises a <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>CancelledError</code></a>.</p> <p>If <code>something()</code> is cancelled by other means (i.e. from within itself) that would also cancel <code>shield()</code>.</p> <p>If it is desired to completely ignore cancellation (not recommended) the <code>shield()</code> function should be combined with a try/except clause, as follows:</p> <pre data-language="python">task = asyncio.create_task(something())
try:
    res = await shield(task)
except CancelledError:
    res = None
</pre> <div class="admonition important"> <p class="admonition-title">Important</p> <p>Save a reference to tasks passed to this function, to avoid a task disappearing mid-execution. The event loop only keeps weak references to tasks. A task that isn’t referenced elsewhere may get garbage collected at any time, even before it’s done.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.10: </span>Deprecation warning is emitted if <em>aw</em> is not Future-like object and there is no running event loop.</p> </div> </dd>
</dl> </section> <section id="timeouts"> <h2>Timeouts</h2> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.timeout">
<code>asyncio.timeout(delay)</code> </dt> <dd>
<p>Return an <a class="reference internal" href="../reference/datamodel#async-context-managers"><span class="std std-ref">asynchronous context manager</span></a> that can be used to limit the amount of time spent waiting on something.</p> <p><em>delay</em> can either be <code>None</code>, or a float/int number of seconds to wait. If <em>delay</em> is <code>None</code>, no time limit will be applied; this can be useful if the delay is unknown when the context manager is created.</p> <p>In either case, the context manager can be rescheduled after creation using <a class="reference internal" href="#asyncio.Timeout.reschedule" title="asyncio.Timeout.reschedule"><code>Timeout.reschedule()</code></a>.</p> <p>Example:</p> <pre data-language="python">async def main():
    async with asyncio.timeout(10):
        await long_running_task()
</pre> <p>If <code>long_running_task</code> takes more than 10 seconds to complete, the context manager will cancel the current task and handle the resulting <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>asyncio.CancelledError</code></a> internally, transforming it into a <a class="reference internal" href="exceptions#TimeoutError" title="TimeoutError"><code>TimeoutError</code></a> which can be caught and handled.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The <a class="reference internal" href="#asyncio.timeout" title="asyncio.timeout"><code>asyncio.timeout()</code></a> context manager is what transforms the <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>asyncio.CancelledError</code></a> into a <a class="reference internal" href="exceptions#TimeoutError" title="TimeoutError"><code>TimeoutError</code></a>, which means the <a class="reference internal" href="exceptions#TimeoutError" title="TimeoutError"><code>TimeoutError</code></a> can only be caught <em>outside</em> of the context manager.</p> </div> <p>Example of catching <a class="reference internal" href="exceptions#TimeoutError" title="TimeoutError"><code>TimeoutError</code></a>:</p> <pre data-language="python">async def main():
    try:
        async with asyncio.timeout(10):
            await long_running_task()
    except TimeoutError:
        print("The long operation timed out, but we've handled it.")

    print("This statement will run regardless.")
</pre> <p>The context manager produced by <a class="reference internal" href="#asyncio.timeout" title="asyncio.timeout"><code>asyncio.timeout()</code></a> can be rescheduled to a different deadline and inspected.</p> <dl class="py class"> <dt class="sig sig-object py" id="asyncio.Timeout">
<code>class asyncio.Timeout(when)</code> </dt> <dd>
<p>An <a class="reference internal" href="../reference/datamodel#async-context-managers"><span class="std std-ref">asynchronous context manager</span></a> for cancelling overdue coroutines.</p> <p><code>when</code> should be an absolute time at which the context should time out, as measured by the event loop’s clock:</p> <ul class="simple"> <li>If <code>when</code> is <code>None</code>, the timeout will never trigger.</li> <li>If <code>when &lt; loop.time()</code>, the timeout will trigger on the next iteration of the event loop.</li> </ul>  <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Timeout.when">
<code>when() → float | None</code> </dt> <dd>
<p>Return the current deadline, or <code>None</code> if the current deadline is not set.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Timeout.reschedule">
<code>reschedule(when: float | None)</code> </dt> <dd>
<p>Reschedule the timeout.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Timeout.expired">
<code>expired() → bool</code> </dt> <dd>
<p>Return whether the context manager has exceeded its deadline (expired).</p> </dd>
</dl>  </dd>
</dl> <p>Example:</p> <pre data-language="python">async def main():
    try:
        # We do not know the timeout when starting, so we pass ``None``.
        async with asyncio.timeout(None) as cm:
            # We know the timeout now, so we reschedule it.
            new_deadline = get_running_loop().time() + 10
            cm.reschedule(new_deadline)

            await long_running_task()
    except TimeoutError:
        pass

    if cm.expired():
        print("Looks like we haven't finished on time.")
</pre> <p>Timeout context managers can be safely nested.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.timeout_at">
<code>asyncio.timeout_at(when)</code> </dt> <dd>
<p>Similar to <a class="reference internal" href="#asyncio.timeout" title="asyncio.timeout"><code>asyncio.timeout()</code></a>, except <em>when</em> is the absolute time to stop waiting, or <code>None</code>.</p> <p>Example:</p> <pre data-language="python">async def main():
    loop = get_running_loop()
    deadline = loop.time() + 20
    try:
        async with asyncio.timeout_at(deadline):
            await long_running_task()
    except TimeoutError:
        print("The long operation timed out, but we've handled it.")

    print("This statement will run regardless.")
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.wait_for">
<code>coroutine asyncio.wait_for(aw, timeout)</code> </dt> <dd>
<p>Wait for the <em>aw</em> <a class="reference internal" href="#asyncio-awaitables"><span class="std std-ref">awaitable</span></a> to complete with a timeout.</p> <p>If <em>aw</em> is a coroutine it is automatically scheduled as a Task.</p> <p><em>timeout</em> can either be <code>None</code> or a float or int number of seconds to wait for. If <em>timeout</em> is <code>None</code>, block until the future completes.</p> <p>If a timeout occurs, it cancels the task and raises <a class="reference internal" href="exceptions#TimeoutError" title="TimeoutError"><code>TimeoutError</code></a>.</p> <p>To avoid the task <a class="reference internal" href="#asyncio.Task.cancel" title="asyncio.Task.cancel"><code>cancellation</code></a>, wrap it in <a class="reference internal" href="#asyncio.shield" title="asyncio.shield"><code>shield()</code></a>.</p> <p>The function will wait until the future is actually cancelled, so the total wait time may exceed the <em>timeout</em>. If an exception happens during cancellation, it is propagated.</p> <p>If the wait is cancelled, the future <em>aw</em> is also cancelled.</p> <p id="asyncio-example-waitfor">Example:</p> <pre data-language="python">async def eternity():
    # Sleep for one hour
    await asyncio.sleep(3600)
    print('yay!')

async def main():
    # Wait for at most 1 second
    try:
        await asyncio.wait_for(eternity(), timeout=1.0)
    except TimeoutError:
        print('timeout!')

asyncio.run(main())

# Expected output:
#
#     timeout!
</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>When <em>aw</em> is cancelled due to a timeout, <code>wait_for</code> waits for <em>aw</em> to be cancelled. Previously, it raised <a class="reference internal" href="exceptions#TimeoutError" title="TimeoutError"><code>TimeoutError</code></a> immediately.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Raises <a class="reference internal" href="exceptions#TimeoutError" title="TimeoutError"><code>TimeoutError</code></a> instead of <a class="reference internal" href="asyncio-exceptions#asyncio.TimeoutError" title="asyncio.TimeoutError"><code>asyncio.TimeoutError</code></a>.</p> </div> </dd>
</dl> </section> <section id="waiting-primitives"> <h2>Waiting Primitives</h2> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.wait">
<code>coroutine asyncio.wait(aws, *, timeout=None, return_when=ALL_COMPLETED)</code> </dt> <dd>
<p>Run <a class="reference internal" href="asyncio-future#asyncio.Future" title="asyncio.Future"><code>Future</code></a> and <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code>Task</code></a> instances in the <em>aws</em> iterable concurrently and block until the condition specified by <em>return_when</em>.</p> <p>The <em>aws</em> iterable must not be empty.</p> <p>Returns two sets of Tasks/Futures: <code>(done, pending)</code>.</p> <p>Usage:</p> <pre data-language="python">done, pending = await asyncio.wait(aws)
</pre> <p><em>timeout</em> (a float or int), if specified, can be used to control the maximum number of seconds to wait before returning.</p> <p>Note that this function does not raise <a class="reference internal" href="exceptions#TimeoutError" title="TimeoutError"><code>TimeoutError</code></a>. Futures or Tasks that aren’t done when the timeout occurs are simply returned in the second set.</p> <p><em>return_when</em> indicates when this function should return. It must be one of the following constants:</p> <table class="docutils align-default">  <thead> <tr>
<th class="head"><p>Constant</p></th> <th class="head"><p>Description</p></th> </tr> </thead>  <tr>
<td><p><code>FIRST_COMPLETED</code></p></td> <td><p>The function will return when any future finishes or is cancelled.</p></td> </tr> <tr>
<td><p><code>FIRST_EXCEPTION</code></p></td> <td><p>The function will return when any future finishes by raising an exception. If no future raises an exception then it is equivalent to <code>ALL_COMPLETED</code>.</p></td> </tr> <tr>
<td><p><code>ALL_COMPLETED</code></p></td> <td><p>The function will return when all futures finish or are cancelled.</p></td> </tr>  </table> <p>Unlike <a class="reference internal" href="#asyncio.wait_for" title="asyncio.wait_for"><code>wait_for()</code></a>, <code>wait()</code> does not cancel the futures when a timeout occurs.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Passing coroutine objects to <code>wait()</code> directly is forbidden.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Added support for generators yielding tasks.</p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.as_completed">
<code>asyncio.as_completed(aws, *, timeout=None)</code> </dt> <dd>
<p>Run <a class="reference internal" href="#asyncio-awaitables"><span class="std std-ref">awaitable objects</span></a> in the <em>aws</em> iterable concurrently. Return an iterator of coroutines. Each coroutine returned can be awaited to get the earliest next result from the iterable of the remaining awaitables.</p> <p>Raises <a class="reference internal" href="exceptions#TimeoutError" title="TimeoutError"><code>TimeoutError</code></a> if the timeout occurs before all Futures are done.</p> <p>Example:</p> <pre data-language="python">for coro in as_completed(aws):
    earliest_result = await coro
    # ...
</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>Removed the <em>loop</em> parameter.</p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.10: </span>Deprecation warning is emitted if not all awaitable objects in the <em>aws</em> iterable are Future-like objects and there is no running event loop.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Added support for generators yielding tasks.</p> </div> </dd>
</dl> </section> <section id="running-in-threads"> <h2>Running in Threads</h2> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.to_thread">
<code>coroutine asyncio.to_thread(func, /, *args, **kwargs)</code> </dt> <dd>
<p>Asynchronously run function <em>func</em> in a separate thread.</p> <p>Any *args and **kwargs supplied for this function are directly passed to <em>func</em>. Also, the current <a class="reference internal" href="contextvars#contextvars.Context" title="contextvars.Context"><code>contextvars.Context</code></a> is propagated, allowing context variables from the event loop thread to be accessed in the separate thread.</p> <p>Return a coroutine that can be awaited to get the eventual result of <em>func</em>.</p> <p>This coroutine function is primarily intended to be used for executing IO-bound functions/methods that would otherwise block the event loop if they were run in the main thread. For example:</p> <pre data-language="python">def blocking_io():
    print(f"start blocking_io at {time.strftime('%X')}")
    # Note that time.sleep() can be replaced with any blocking
    # IO-bound operation, such as file operations.
    time.sleep(1)
    print(f"blocking_io complete at {time.strftime('%X')}")

async def main():
    print(f"started main at {time.strftime('%X')}")

    await asyncio.gather(
        asyncio.to_thread(blocking_io),
        asyncio.sleep(1))

    print(f"finished main at {time.strftime('%X')}")


asyncio.run(main())

# Expected output:
#
# started main at 19:50:53
# start blocking_io at 19:50:53
# blocking_io complete at 19:50:54
# finished main at 19:50:54
</pre> <p>Directly calling <code>blocking_io()</code> in any coroutine would block the event loop for its duration, resulting in an additional 1 second of run time. Instead, by using <code>asyncio.to_thread()</code>, we can run it in a separate thread without blocking the event loop.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Due to the <a class="reference internal" href="../glossary#term-GIL"><span class="xref std std-term">GIL</span></a>, <code>asyncio.to_thread()</code> can typically only be used to make IO-bound functions non-blocking. However, for extension modules that release the GIL or alternative Python implementations that don’t have one, <code>asyncio.to_thread()</code> can also be used for CPU-bound functions.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.9.</span></p> </div> </dd>
</dl> </section> <section id="scheduling-from-other-threads"> <h2>Scheduling From Other Threads</h2> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.run_coroutine_threadsafe">
<code>asyncio.run_coroutine_threadsafe(coro, loop)</code> </dt> <dd>
<p>Submit a coroutine to the given event loop. Thread-safe.</p> <p>Return a <a class="reference internal" href="concurrent.futures#concurrent.futures.Future" title="concurrent.futures.Future"><code>concurrent.futures.Future</code></a> to wait for the result from another OS thread.</p> <p>This function is meant to be called from a different OS thread than the one where the event loop is running. Example:</p> <pre data-language="python"># Create a coroutine
coro = asyncio.sleep(1, result=3)

# Submit the coroutine to a given loop
future = asyncio.run_coroutine_threadsafe(coro, loop)

# Wait for the result with an optional timeout argument
assert future.result(timeout) == 3
</pre> <p>If an exception is raised in the coroutine, the returned Future will be notified. It can also be used to cancel the task in the event loop:</p> <pre data-language="python">try:
    result = future.result(timeout)
except TimeoutError:
    print('The coroutine took too long, cancelling the task...')
    future.cancel()
except Exception as exc:
    print(f'The coroutine raised an exception: {exc!r}')
else:
    print(f'The coroutine returned: {result!r}')
</pre> <p>See the <a class="reference internal" href="asyncio-dev#asyncio-multithreading"><span class="std std-ref">concurrency and multithreading</span></a> section of the documentation.</p> <p>Unlike other asyncio functions this function requires the <em>loop</em> argument to be passed explicitly.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.1.</span></p> </div> </dd>
</dl> </section> <section id="introspection"> <h2>Introspection</h2> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.current_task">
<code>asyncio.current_task(loop=None)</code> </dt> <dd>
<p>Return the currently running <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code>Task</code></a> instance, or <code>None</code> if no task is running.</p> <p>If <em>loop</em> is <code>None</code> <a class="reference internal" href="asyncio-eventloop#asyncio.get_running_loop" title="asyncio.get_running_loop"><code>get_running_loop()</code></a> is used to get the current loop.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.all_tasks">
<code>asyncio.all_tasks(loop=None)</code> </dt> <dd>
<p>Return a set of not yet finished <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code>Task</code></a> objects run by the loop.</p> <p>If <em>loop</em> is <code>None</code>, <a class="reference internal" href="asyncio-eventloop#asyncio.get_running_loop" title="asyncio.get_running_loop"><code>get_running_loop()</code></a> is used for getting current loop.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </dd>
</dl> <dl class="py function"> <dt class="sig sig-object py" id="asyncio.iscoroutine">
<code>asyncio.iscoroutine(obj)</code> </dt> <dd>
<p>Return <code>True</code> if <em>obj</em> is a coroutine object.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </dd>
</dl> </section> <section id="task-object"> <h2>Task Object</h2> <dl class="py class"> <dt class="sig sig-object py" id="asyncio.Task">
<code>class asyncio.Task(coro, *, loop=None, name=None, context=None, eager_start=False)</code> </dt> <dd>
<p>A <a class="reference internal" href="asyncio-future#asyncio.Future" title="asyncio.Future"><code>Future-like</code></a> object that runs a Python <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine</span></a>. Not thread-safe.</p> <p>Tasks are used to run coroutines in event loops. If a coroutine awaits on a Future, the Task suspends the execution of the coroutine and waits for the completion of the Future. When the Future is <em>done</em>, the execution of the wrapped coroutine resumes.</p> <p>Event loops use cooperative scheduling: an event loop runs one Task at a time. While a Task awaits for the completion of a Future, the event loop runs other Tasks, callbacks, or performs IO operations.</p> <p>Use the high-level <a class="reference internal" href="#asyncio.create_task" title="asyncio.create_task"><code>asyncio.create_task()</code></a> function to create Tasks, or the low-level <a class="reference internal" href="asyncio-eventloop#asyncio.loop.create_task" title="asyncio.loop.create_task"><code>loop.create_task()</code></a> or <a class="reference internal" href="asyncio-future#asyncio.ensure_future" title="asyncio.ensure_future"><code>ensure_future()</code></a> functions. Manual instantiation of Tasks is discouraged.</p> <p>To cancel a running Task use the <a class="reference internal" href="#asyncio.Task.cancel" title="asyncio.Task.cancel"><code>cancel()</code></a> method. Calling it will cause the Task to throw a <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>CancelledError</code></a> exception into the wrapped coroutine. If a coroutine is awaiting on a Future object during cancellation, the Future object will be cancelled.</p> <p><a class="reference internal" href="#asyncio.Task.cancelled" title="asyncio.Task.cancelled"><code>cancelled()</code></a> can be used to check if the Task was cancelled. The method returns <code>True</code> if the wrapped coroutine did not suppress the <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>CancelledError</code></a> exception and was actually cancelled.</p> <p><a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code>asyncio.Task</code></a> inherits from <a class="reference internal" href="asyncio-future#asyncio.Future" title="asyncio.Future"><code>Future</code></a> all of its APIs except <a class="reference internal" href="asyncio-future#asyncio.Future.set_result" title="asyncio.Future.set_result"><code>Future.set_result()</code></a> and <a class="reference internal" href="asyncio-future#asyncio.Future.set_exception" title="asyncio.Future.set_exception"><code>Future.set_exception()</code></a>.</p> <p>An optional keyword-only <em>context</em> argument allows specifying a custom <a class="reference internal" href="contextvars#contextvars.Context" title="contextvars.Context"><code>contextvars.Context</code></a> for the <em>coro</em> to run in. If no <em>context</em> is provided, the Task copies the current context and later runs its coroutine in the copied context.</p> <p>An optional keyword-only <em>eager_start</em> argument allows eagerly starting the execution of the <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code>asyncio.Task</code></a> at task creation time. If set to <code>True</code> and the event loop is running, the task will start executing the coroutine immediately, until the first time the coroutine blocks. If the coroutine returns or raises without blocking, the task will be finished eagerly and will skip scheduling to the event loop.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Added support for the <a class="reference internal" href="contextvars#module-contextvars" title="contextvars: Context Variables"><code>contextvars</code></a> module.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>Added the <em>name</em> parameter.</p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.10: </span>Deprecation warning is emitted if <em>loop</em> is not specified and there is no running event loop.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Added the <em>context</em> parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Added the <em>eager_start</em> parameter.</p> </div> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Task.done">
<code>done()</code> </dt> <dd>
<p>Return <code>True</code> if the Task is <em>done</em>.</p> <p>A Task is <em>done</em> when the wrapped coroutine either returned a value, raised an exception, or the Task was cancelled.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Task.result">
<code>result()</code> </dt> <dd>
<p>Return the result of the Task.</p> <p>If the Task is <em>done</em>, the result of the wrapped coroutine is returned (or if the coroutine raised an exception, that exception is re-raised.)</p> <p>If the Task has been <em>cancelled</em>, this method raises a <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>CancelledError</code></a> exception.</p> <p>If the Task’s result isn’t yet available, this method raises a <a class="reference internal" href="asyncio-exceptions#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code>InvalidStateError</code></a> exception.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Task.exception">
<code>exception()</code> </dt> <dd>
<p>Return the exception of the Task.</p> <p>If the wrapped coroutine raised an exception that exception is returned. If the wrapped coroutine returned normally this method returns <code>None</code>.</p> <p>If the Task has been <em>cancelled</em>, this method raises a <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>CancelledError</code></a> exception.</p> <p>If the Task isn’t <em>done</em> yet, this method raises an <a class="reference internal" href="asyncio-exceptions#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code>InvalidStateError</code></a> exception.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Task.add_done_callback">
<code>add_done_callback(callback, *, context=None)</code> </dt> <dd>
<p>Add a callback to be run when the Task is <em>done</em>.</p> <p>This method should only be used in low-level callback-based code.</p> <p>See the documentation of <a class="reference internal" href="asyncio-future#asyncio.Future.add_done_callback" title="asyncio.Future.add_done_callback"><code>Future.add_done_callback()</code></a> for more details.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Task.remove_done_callback">
<code>remove_done_callback(callback)</code> </dt> <dd>
<p>Remove <em>callback</em> from the callbacks list.</p> <p>This method should only be used in low-level callback-based code.</p> <p>See the documentation of <a class="reference internal" href="asyncio-future#asyncio.Future.remove_done_callback" title="asyncio.Future.remove_done_callback"><code>Future.remove_done_callback()</code></a> for more details.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Task.get_stack">
<code>get_stack(*, limit=None)</code> </dt> <dd>
<p>Return the list of stack frames for this Task.</p> <p>If the wrapped coroutine is not done, this returns the stack where it is suspended. If the coroutine has completed successfully or was cancelled, this returns an empty list. If the coroutine was terminated by an exception, this returns the list of traceback frames.</p> <p>The frames are always ordered from oldest to newest.</p> <p>Only one stack frame is returned for a suspended coroutine.</p> <p>The optional <em>limit</em> argument sets the maximum number of frames to return; by default all available frames are returned. The ordering of the returned list differs depending on whether a stack or a traceback is returned: the newest frames of a stack are returned, but the oldest frames of a traceback are returned. (This matches the behavior of the traceback module.)</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Task.print_stack">
<code>print_stack(*, limit=None, file=None)</code> </dt> <dd>
<p>Print the stack or traceback for this Task.</p> <p>This produces output similar to that of the traceback module for the frames retrieved by <a class="reference internal" href="#asyncio.Task.get_stack" title="asyncio.Task.get_stack"><code>get_stack()</code></a>.</p> <p>The <em>limit</em> argument is passed to <a class="reference internal" href="#asyncio.Task.get_stack" title="asyncio.Task.get_stack"><code>get_stack()</code></a> directly.</p> <p>The <em>file</em> argument is an I/O stream to which the output is written; by default output is written to <a class="reference internal" href="sys#sys.stdout" title="sys.stdout"><code>sys.stdout</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Task.get_coro">
<code>get_coro()</code> </dt> <dd>
<p>Return the coroutine object wrapped by the <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code>Task</code></a>.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>This will return <code>None</code> for Tasks which have already completed eagerly. See the <a class="reference internal" href="#eager-task-factory"><span class="std std-ref">Eager Task Factory</span></a>.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Newly added eager task execution means result may be <code>None</code>.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Task.get_context">
<code>get_context()</code> </dt> <dd>
<p>Return the <a class="reference internal" href="contextvars#contextvars.Context" title="contextvars.Context"><code>contextvars.Context</code></a> object associated with the task.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Task.get_name">
<code>get_name()</code> </dt> <dd>
<p>Return the name of the Task.</p> <p>If no name has been explicitly assigned to the Task, the default asyncio Task implementation generates a default name during instantiation.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Task.set_name">
<code>set_name(value)</code> </dt> <dd>
<p>Set the name of the Task.</p> <p>The <em>value</em> argument can be any object, which is then converted to a string.</p> <p>In the default Task implementation, the name will be visible in the <a class="reference internal" href="functions#repr" title="repr"><code>repr()</code></a> output of a task object.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Task.cancel">
<code>cancel(msg=None)</code> </dt> <dd>
<p>Request the Task to be cancelled.</p> <p>This arranges for a <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>CancelledError</code></a> exception to be thrown into the wrapped coroutine on the next cycle of the event loop.</p> <p>The coroutine then has a chance to clean up or even deny the request by suppressing the exception with a <a class="reference internal" href="../reference/compound_stmts#try"><code>try</code></a> … … <code>except CancelledError</code> … <a class="reference internal" href="../reference/compound_stmts#finally"><code>finally</code></a> block. Therefore, unlike <a class="reference internal" href="asyncio-future#asyncio.Future.cancel" title="asyncio.Future.cancel"><code>Future.cancel()</code></a>, <a class="reference internal" href="#asyncio.Task.cancel" title="asyncio.Task.cancel"><code>Task.cancel()</code></a> does not guarantee that the Task will be cancelled, although suppressing cancellation completely is not common and is actively discouraged. Should the coroutine nevertheless decide to suppress the cancellation, it needs to call <a class="reference internal" href="#asyncio.Task.uncancel" title="asyncio.Task.uncancel"><code>Task.uncancel()</code></a> in addition to catching the exception.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>Added the <em>msg</em> parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>The <code>msg</code> parameter is propagated from cancelled task to its awaiter.</p> </div> <p id="asyncio-example-task-cancel">The following example illustrates how coroutines can intercept the cancellation request:</p> <pre data-language="python">async def cancel_me():
    print('cancel_me(): before sleep')

    try:
        # Wait for 1 hour
        await asyncio.sleep(3600)
    except asyncio.CancelledError:
        print('cancel_me(): cancel sleep')
        raise
    finally:
        print('cancel_me(): after sleep')

async def main():
    # Create a "cancel_me" Task
    task = asyncio.create_task(cancel_me())

    # Wait for 1 second
    await asyncio.sleep(1)

    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print("main(): cancel_me is cancelled now")

asyncio.run(main())

# Expected output:
#
#     cancel_me(): before sleep
#     cancel_me(): cancel sleep
#     cancel_me(): after sleep
#     main(): cancel_me is cancelled now
</pre> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Task.cancelled">
<code>cancelled()</code> </dt> <dd>
<p>Return <code>True</code> if the Task is <em>cancelled</em>.</p> <p>The Task is <em>cancelled</em> when the cancellation was requested with <a class="reference internal" href="#asyncio.Task.cancel" title="asyncio.Task.cancel"><code>cancel()</code></a> and the wrapped coroutine propagated the <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>CancelledError</code></a> exception thrown into it.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Task.uncancel">
<code>uncancel()</code> </dt> <dd>
<p>Decrement the count of cancellation requests to this Task.</p> <p>Returns the remaining number of cancellation requests.</p> <p>Note that once execution of a cancelled task completed, further calls to <a class="reference internal" href="#asyncio.Task.uncancel" title="asyncio.Task.uncancel"><code>uncancel()</code></a> are ineffective.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> <p>This method is used by asyncio’s internals and isn’t expected to be used by end-user code. In particular, if a Task gets successfully uncancelled, this allows for elements of structured concurrency like <a class="reference internal" href="#taskgroups"><span class="std std-ref">Task Groups</span></a> and <a class="reference internal" href="#asyncio.timeout" title="asyncio.timeout"><code>asyncio.timeout()</code></a> to continue running, isolating cancellation to the respective structured block. For example:</p> <pre data-language="python">async def make_request_with_timeout():
    try:
        async with asyncio.timeout(1):
            # Structured block affected by the timeout:
            await make_request()
            await make_another_request()
    except TimeoutError:
        log("There was a timeout")
    # Outer code not affected by the timeout:
    await unrelated_code()
</pre> <p>While the block with <code>make_request()</code> and <code>make_another_request()</code> might get cancelled due to the timeout, <code>unrelated_code()</code> should continue running even in case of the timeout. This is implemented with <a class="reference internal" href="#asyncio.Task.uncancel" title="asyncio.Task.uncancel"><code>uncancel()</code></a>. <a class="reference internal" href="#asyncio.TaskGroup" title="asyncio.TaskGroup"><code>TaskGroup</code></a> context managers use <a class="reference internal" href="#asyncio.Task.uncancel" title="asyncio.Task.uncancel"><code>uncancel()</code></a> in a similar fashion.</p> <p>If end-user code is, for some reason, suppresing cancellation by catching <a class="reference internal" href="asyncio-exceptions#asyncio.CancelledError" title="asyncio.CancelledError"><code>CancelledError</code></a>, it needs to call this method to remove the cancellation state.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="asyncio.Task.cancelling">
<code>cancelling()</code> </dt> <dd>
<p>Return the number of pending cancellation requests to this Task, i.e., the number of calls to <a class="reference internal" href="#asyncio.Task.cancel" title="asyncio.Task.cancel"><code>cancel()</code></a> less the number of <a class="reference internal" href="#asyncio.Task.uncancel" title="asyncio.Task.uncancel"><code>uncancel()</code></a> calls.</p> <p>Note that if this number is greater than zero but the Task is still executing, <a class="reference internal" href="#asyncio.Task.cancelled" title="asyncio.Task.cancelled"><code>cancelled()</code></a> will still return <code>False</code>. This is because this number can be lowered by calling <a class="reference internal" href="#asyncio.Task.uncancel" title="asyncio.Task.uncancel"><code>uncancel()</code></a>, which can lead to the task not being cancelled after all if the cancellation requests go down to zero.</p> <p>This method is used by asyncio’s internals and isn’t expected to be used by end-user code. See <a class="reference internal" href="#asyncio.Task.uncancel" title="asyncio.Task.uncancel"><code>uncancel()</code></a> for more details.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> </dd>
</dl> </dd>
</dl> </section> <div class="_attribution">
  <p class="_attribution-p">
    &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
    <a href="https://docs.python.org/3.12/library/asyncio-task.html" class="_attribution-link">https://docs.python.org/3.12/library/asyncio-task.html</a>
  </p>
</div>