[Tut] Python Async Function - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: Python (https://www.sickgaming.net/forum-83.html) +--- Thread: [Tut] Python Async Function (/thread-101113.html) |
[Tut] Python Async Function - xSicKxBot - 05-08-2023 Python Async Function <div> <div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload='{"align":"left","id":"1343721","slug":"default","valign":"top","ignore":"","reference":"auto","class":"","count":"1","legendonly":"","readonly":"","score":"5","starsonly":"","best":"5","gap":"5","greet":"Rate this post","legend":"5\/5 - (1 vote)","size":"24","title":"Python Async Function","width":"142.5","_legend":"{score}\/{best} - ({count} {votes})","font_factor":"1.25"}'> <div class="kksr-stars"> <div class="kksr-stars-inactive"> <div class="kksr-star" data-star="1" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="2" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="3" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="4" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="5" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> </p></div> <div class="kksr-stars-active" style="width: 142.5px;"> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> </p></div> </div> <div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div> </p></div> <p>As a Python developer, you might have encountered the terms <code>async</code> and <code>await</code>, wondering what they are and how to use them in your projects.</p> <p class="has-global-color-8-background-color has-background"><strong>Async functions enable you to write concurrent code using the <code>async</code>/<code>await</code> syntax</strong>. This powerful duo allows you to perform multiple tasks simultaneously without blocking the execution of your code. <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f6e0.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Think of it as having multiple browser tabs open; while one page loads, you can continue browsing other tabs. This capability means your Python applications can become faster, more efficient, and capable of handling many I/O operations. <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f31f.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p> <p>To get started with <code>async</code> functions, you’ll need to get acquainted with Python’s <code>asyncio</code> library, which serves as a foundation for numerous asynchronous frameworks such as high-performance network and web servers, database connection libraries, and distributed task queues. <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f517.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p> <p>Mastering async functions can truly elevate your Python programming skills and help you build powerful and responsive applications. <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f40d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p> <h2 class="wp-block-heading">Python Async Function Basics</h2> <div class="wp-block-image"> <figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="920" height="517" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-80.png" alt="" class="wp-image-1343744" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-80.png 920w, https://blog.finxter.com/wp-content/uploads/2023/05/image-80-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2023/05/image-80-768x432.png 768w" sizes="(max-width: 920px) 100vw, 920px" /></figure> </div> <p>First, you’ll learn the basics of Python <code>async</code> functions, which can help improve the performance of your asynchronous programming. </p> <p>We’ll cover </p> <ul> <li>async functions without <code>await</code>, </li> <li>an async function example, async function return, and </li> <li>async function call. </li> </ul> <h3 class="wp-block-heading">Async Function Without Await</h3> <p>You might wonder if it’s possible to create an async function without using the <code>await</code> keyword. Well, it is! </p> <p>However, without <code>await</code>, the async function becomes somewhat less useful, since you won’t be able to pause its execution and yield control back to the event loop. </p> <p>This means your async code will not be able to achieve cooperative concurrency, and other coroutines might be stuck waiting for their turn to execute. It’s generally a good idea to use <code>await</code> when working with async functions for more efficient asynchronous programming.</p> <h3 class="wp-block-heading">Async Function Example</h3> <p>Let’s dive into a simple example of using an async function in Python with <code>asyncio</code>:</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import asyncio async def greet(name: str): print(f"Hello, {name}!") await asyncio.sleep(1) print(f"Nice to meet you, {name}!") async def main(): task1 = asyncio.create_task(greet("Alice")) task2 = asyncio.create_task(greet("Bob")) await task1 await task2 asyncio.run(main()) </pre> <div class="wp-block-image"> <figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="897" height="245" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-78.png" alt="" class="wp-image-1343728" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-78.png 897w, https://blog.finxter.com/wp-content/uploads/2023/05/image-78-300x82.png 300w, https://blog.finxter.com/wp-content/uploads/2023/05/image-78-768x210.png 768w" sizes="(max-width: 897px) 100vw, 897px" /></figure> </div> <p>In this example, an async function <code>greet</code> is declared, which prints a greeting message, waits for 1 second using <code>asyncio.sleep</code>, and then prints another message. </p> <p>The <code>main</code> asynchronous function creates two tasks to call <code>greet</code> with different names, running them concurrently. </p> <h3 class="wp-block-heading">Async Function Return</h3> <p class="has-global-color-8-background-color has-background">When you want to return a value from an async function, just use the <code>return</code> statement as you would in regular functions. However, keep in mind that the returned value will be wrapped in an <code>asyncio.Future</code> object, not the actual value. </p> <p>You’ll need to use <code>await</code> to get the value when calling this async function.</p> <p>For example:</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">async def calculate_result(): await asyncio.sleep(1) return "Result!" async def main(): result = await calculate_result() print(result) asyncio.run(main()) </pre> <p>Here, <code>calculate_result</code> is an async function that returns a value after asynchronously waiting for 1 second. In the <code>main()</code> function, you can use <code>await</code> to get the actual value and <a href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank" rel="noreferrer noopener">print</a> it. <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f31f.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p> <h3 class="wp-block-heading">Async Function Call</h3> <p class="has-global-color-8-background-color has-background">To call an async function, you can’t simply use the normal function call syntax, because doing so would just return a coroutine object, not the actual result of the function. Instead, you have to use the <code>await</code> keyword to call the async function, or use <code>asyncio.create_task</code> or similar functions to run it concurrently:</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Using `await` to call async function result = await async_function() # Using `asyncio.create_task` to run concurrently task = asyncio.create_task(async_function()) </pre> <p>Remember to always use the appropriate method to call your async functions in order to achieve efficient asynchronous programming with Python’s powerful <code>async/await</code> syntax. </p> <h2 class="wp-block-heading">Advanced Async Function Concepts</h2> <div class="wp-block-image"> <figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="920" height="613" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-81.png" alt="" class="wp-image-1343745" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-81.png 920w, https://blog.finxter.com/wp-content/uploads/2023/05/image-81-300x200.png 300w, https://blog.finxter.com/wp-content/uploads/2023/05/image-81-768x512.png 768w" sizes="(max-width: 920px) 100vw, 920px" /></figure> </div> <p>Next, you’ll explore advanced async function concepts to give you a better understanding of how they work in Python. <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f60a.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Ready? Let’s dive in!</p> <h3 class="wp-block-heading">Async Function Decorator</h3> <p class="has-global-color-8-background-color has-background">To create an async function, you’ll use the <code>async def</code> syntax. This means you don’t have to use a <a href="https://blog.finxter.com/an-introduction-to-closures-and-decorators-in-python/" data-type="post" data-id="33290" target="_blank" rel="noreferrer noopener">decorator</a>, but you can still decorate asynchronous functions with the <code>@some_decorator</code> syntax for better modularity in your programs.</p> <p>For instance, consider using <code>@asyncio.coroutine</code> with a <code>yield from</code> syntax if you’re working with Python 3.4 or earlier. Or simply <a href="https://blog.finxter.com/how-to-install-python/" data-type="post" data-id="17770" target="_blank" rel="noreferrer noopener">upgrade</a> to newer versions! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f605.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p> <h3 class="wp-block-heading">Async Function Type Hint</h3> <p class="has-global-color-8-background-color has-background"><strong>Type hints</strong> help improve the readability of your async code. Specify the input and output types of your async function using the <code>typing</code> module’s Coroutine and <code>asyncio</code>‘s Future objects. </p> <p>Here’s an example:</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from typing import Coroutine import asyncio async def some_async_function() -> Coroutine[str]: await asyncio.sleep(1) return "done" </pre> <h3 class="wp-block-heading">Async Function Returns Coroutine</h3> <p class="has-global-color-8-background-color has-background">An async function, also known as a coroutine, returns a coroutine object when called. You can use it as a direct call or pass it to an event loop to run the async function using <code>asyncio.run()</code> or <code>loop.run_until_complete()</code>. </p> <p>Keep in mind coroutine objects aren’t executed until you explicitly use an event loop or an <code>await</code> expression.</p> <h3 class="wp-block-heading">Async Function Await</h3> <p>When writing async functions, the <code>await</code> keyword is crucial. It allows you to pause the execution of a coroutine and wait for a result without blocking other coroutines. </p> <p>You’ll often use <code>await</code> with I/O-bound operations, like reading from files, interacting with network services, or retrieving resources, which can take a significant amount of time.</p> <p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/2b50.png" alt="⭐" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/python-__await__-magic-method/" data-type="URL" data-id="https://blog.finxter.com/python-__await__-magic-method/" target="_blank" rel="noreferrer noopener">Python <code>__await()__</code> Magic Method</a></p> <h3 class="wp-block-heading">Async Function Type</h3> <p>An async function’s type is <code>coroutine</code>. So when defining your async function, you’re essentially creating a non-blocking function that allows other functions to run while it waits for results. </p> <p>To check if an object in Python is a coroutine, you can use <code>inspect.iscoroutine(obj)</code> or <code>inspect.iscoroutinefunction(obj)</code>.</p> <h3 class="wp-block-heading">Async Function Return Type</h3> <p class="has-global-color-8-background-color has-background">Async functions return a <code>coroutine</code> object, but you can also specify the type of the eventual returned value. For instance, if your async function performs some networking tasks and <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-return-a-json-object-from-a-function-in-python/" data-type="post" data-id="985215" target="_blank">returns JSON</a> data, you can specify the return type as <code>Dict[str, Any]</code>. </p> <p>Here’s how you do that:</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from typing import Dict, Any, Coroutine import asyncio async def fetch_json_data() -> Coroutine[Dict[str, Any]]: # some networking tasks here await asyncio.sleep(2) return {"key": "value"} </pre> <h2 class="wp-block-heading">Async Function in Different Contexts</h2> <div class="wp-block-image"> <figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="920" height="637" src="https://blog.finxter.com/wp-content/uploads/2023/05/image-82.png" alt="" class="wp-image-1343746" srcset="https://blog.finxter.com/wp-content/uploads/2023/05/image-82.png 920w, https://blog.finxter.com/wp-content/uploads/2023/05/image-82-300x208.png 300w, https://blog.finxter.com/wp-content/uploads/2023/05/image-82-768x532.png 768w" sizes="(max-width: 920px) 100vw, 920px" /></figure> </div> <p>In this section, we will explore using async functions in different circumstances, such as within classes, threads, and converting async functions to sync. We will also discuss the concepts of async function sleep and handling functions that were never awaited. </p> <h3 class="wp-block-heading">Async Function in Class</h3> <p class="has-global-color-8-background-color has-background">When working with classes in Python, you might want to include asynchronous methods. To achieve this, just define your class method with <code>async def</code>. Remember to <code>await</code> your async methods when calling them to ensure proper execution. </p> <p>Here’s an example:</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class MyClass: async def my_async_method(self): await asyncio.sleep(1) async def main(): my_obj = MyClass() await my_obj.my_async_method() </pre> <h3 class="wp-block-heading">Async Function in Thread</h3> <p class="has-global-color-8-background-color has-background">Running async functions in a thread can be tricky due to event loop requirements. Use <code>asyncio.to_thread()</code> for running async functions in threads. This will ensure your async function is executed within the correct thread’s event loop. </p> <p>For example:</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">async def my_async_function(): await asyncio.sleep(1) print("Hello from async function!") async def main(): result = await asyncio.to_thread(my_async_function) </pre> <h3 class="wp-block-heading">Async Function to Sync</h3> <p>If you need to call an async function from synchronous code, you can use <code>asyncio.run()</code> or create an event loop that runs a given coroutine.</p> <p>Here’s an example of how to run an async function from sync code:</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def sync_function(): asyncio.run(my_async_function()) </pre> <h3 class="wp-block-heading">Async Function Sleep</h3> <p>Sometimes, you might want to introduce a delay in your coroutine using <code>asyncio.sleep</code>. This allows other coroutines to run while waiting for IO operations or other events. </p> <p>Example:</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">async def delayed_hello(): await asyncio.sleep(1) print("Hello after 1 second!") </pre> <p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/time-delay-in-python/" data-type="post" data-id="138154" target="_blank" rel="noreferrer noopener">Time Delay in Python</a></p> <h3 class="wp-block-heading">Async Function Was Never Awaited</h3> <p>In some cases, you may forget to <code>await</code> an async function, which leads to warnings such as <code>"coroutine 'my_async_function' was never awaited."</code> </p> <p>To prevent these issues, always ensure you’re using <code>await</code> when calling async functions:</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">async def my_async_function(): await asyncio.sleep(1) async def main(): # Missing 'await' would lead to a warning await my_async_function() </pre> <p>If you got something out of this article, I’m sure you’ll learn something of this one: <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p> <p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/python-async-with-statement-simplifying-asynchronous-code/" data-type="URL" data-id="https://blog.finxter.com/python-async-with-statement-simplifying-asynchronous-code/" target="_blank" rel="noreferrer noopener">Python Async With Statement — Simplifying Asynchronous Code</a></p> <p>I promise it has more beautiful pics. <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f605.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p> </div> https://www.sickgaming.net/blog/2023/05/07/python-async-function/ |