{"id":331,"date":"2024-01-28T11:00:03","date_gmt":"2024-01-28T11:00:03","guid":{"rendered":"https:\/\/learnpython.elegantwallp.com\/?p=331"},"modified":"2024-01-28T11:00:04","modified_gmt":"2024-01-28T11:00:04","slug":"python-asyncio-wait","status":"publish","type":"post","link":"https:\/\/learnpython.elegantwallp.com\/2024\/01\/28\/python-asyncio-wait\/","title":{"rendered":"Python asyncio.wait()"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you\u2019ll learn about the&nbsp;<code>asyncio.wait()<\/code>&nbsp;function to run an iterable of awaitable objects concurrently.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to the Python asyncio wait() function<\/h2>\n\n\n\n<p>The&nbsp;<code>asyncio.wait()<\/code>&nbsp;function runs an iterable of awaitables objects and blocks until a specified condition.<\/p>\n\n\n\n<p>Here\u2019s the syntax of the\u00a0<code>asyncio.wait()<\/code>\u00a0function:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>asyncio.wait(aws, *, timeout=None, return_when=ALL_COMPLETED)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>The&nbsp;<code>asyncio.wait()<\/code>&nbsp;function has the following parameters:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>aws<\/code>&nbsp;is iterable of awaitable objects that you want to run concurrently.<\/li>\n\n\n\n<li><code>timeout<\/code>&nbsp;(either&nbsp;<code>int<\/code>&nbsp;or&nbsp;<code>float<\/code>) specifies a maximum number of seconds to wait before returning the result.<\/li>\n\n\n\n<li><code>return_when<\/code>&nbsp;indicates when the function should return. The&nbsp;<code>return_when<\/code>&nbsp;accepts one of the constants in the table below.<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Constant<\/th><th>Description<\/th><\/tr><\/thead><tbody><tr><td><code>FIRST_COMPLETED<\/code><\/td><td>Return when all awaitables are complete or canceled.<\/td><\/tr><tr><td><code>FIRST_EXCEPTION<\/code><\/td><td>Return when any awaitable is complete by raising an exception. If no awaitable raises an exception, the&nbsp;<code>FIRST_EXCEPTION<\/code>&nbsp;is equivalent to&nbsp;<code>ALL_COMPLETED<\/code>.<\/td><\/tr><tr><td><code>ALL_COMPLETED<\/code><\/td><td>Return when all awaitables are complete or cancelled.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Note that these constants are in the&nbsp;<code>asyncio<\/code>&nbsp;library so you can reference them like&nbsp;<code>asyncio.FIRST_COMPLETED<\/code><\/p>\n\n\n\n<p>The\u00a0<code>asyncio.wait()<\/code>\u00a0returns two sets:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>done, pending = await asyncio.wait(aws)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\" id=\"block-95391e0d-c825-4754-b829-392a1cfd4309\">\n<li><code>done<\/code>&nbsp;is a set of awaitables that are done.<\/li>\n\n\n\n<li><code>pending<\/code>&nbsp;is a set of awaitables that are pending.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Python asyncio wait() function examples<\/h2>\n\n\n\n<p>The following example illustrates how to use the\u00a0<code>asyncio.wait()<\/code>\u00a0function:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>import asyncio from asyncio import create_task class APIError(Exception): pass async def call_api(message, result=100, delay=3, raise_exception=False): print(message) await asyncio.sleep(delay) if raise_exception: raise APIError else: return result async def main(): task_1 = create_task(call_api('calling API 1...', result=1, delay=1)) task_2 = create_task(call_api('calling API 2...', result=2, delay=2)) task_3 = create_task(call_api('calling API 3...', result=3, delay=3)) pending = (task_1, task_2, task_3) while pending: done, pending = await asyncio.wait( pending, return_when=asyncio.FIRST_COMPLETED ) result = done.pop().result() print(result) asyncio.run(main())<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>How it works.<\/p>\n\n\n\n<p>First, define the\u00a0<code>APIError<\/code>\u00a0class that extends the\u00a0<code>Exception<\/code>\u00a0class:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class APIError(Exception): pass<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Second, define the\u00a0<code>call_api()<\/code>\u00a0function that simulates an asynchronous operation:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>async def call_api(message, result=100, delay=3, raise_exception=False): print(message) await asyncio.sleep(delay) if raise_exception: raise APIError else: return result<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Third, create three tasks that wrap the\u00a0<code>call_api()<\/code>\u00a0coroutines. Each coroutine returns a different number:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>task_1 = create_task(call_api('calling API 1...', result=1, delay=1)) task_2 = create_task(call_api('calling API 2...', result=2, delay=2)) task_3 = create_task(call_api('calling API 3...', result=3, delay=3)) pending = (task_1, task_2, task_3)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Finally, call the\u00a0<code>asyncio.wait()<\/code>\u00a0function to run the tasks inside a\u00a0<code><a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-while\/\">while<\/a><\/code>\u00a0loop. If all the tasks are complete, the pending will be empty, and the\u00a0<code>while<\/code>\u00a0loop will exit. In each iteration, we get the completed task from the\u00a0<code>done<\/code>\u00a0set and display the result:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>while pending: done, pending = await asyncio.wait( pending, return_when=asyncio.FIRST_COMPLETED ) result = done.pop().result() print(result)<\/code><\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Summary: in this tutorial, you\u2019ll learn about the&nbsp;asyncio.wait()&nbsp;function to run an iterable of awaitable objects concurrently. Introduction to the Python asyncio wait() function The&nbsp;asyncio.wait()&nbsp;function runs an iterable of awaitables objects and blocks until a specified condition. Here\u2019s the syntax of the\u00a0asyncio.wait()\u00a0function: The&nbsp;asyncio.wait()&nbsp;function has the following parameters: Constant Description FIRST_COMPLETED Return when all awaitables are complete [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[41],"tags":[],"class_list":["post-331","post","type-post","status-publish","format-standard","hentry","category-1-python-concurrency"],"_links":{"self":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/331","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/comments?post=331"}],"version-history":[{"count":1,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/331\/revisions"}],"predecessor-version":[{"id":332,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/331\/revisions\/332"}],"wp:attachment":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/media?parent=331"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/categories?post=331"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/tags?post=331"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}