{"id":134869,"date":"2023-09-20T09:15:42","date_gmt":"2023-09-20T09:15:42","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=1651678"},"modified":"2023-09-20T09:15:42","modified_gmt":"2023-09-20T09:15:42","slug":"python-async-generator-mastering-asyncio-in-modern-applications","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2023\/09\/20\/python-async-generator-mastering-asyncio-in-modern-applications\/","title":{"rendered":"Python Async Generator: Mastering Asyncio in Modern Applications"},"content":{"rendered":"\n<div class=\"kk-star-ratings kksr-auto kksr-align-left kksr-valign-top\" data-payload='{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;1651678&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;legendonly&quot;:&quot;&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;starsonly&quot;:&quot;&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\\\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;title&quot;:&quot;Python Async Generator: Mastering Asyncio in Modern Applications&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\\\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}'>\n<div class=\"kksr-stars\">\n<div class=\"kksr-stars-inactive\">\n<div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"kksr-stars-active\" style=\"width: 142.5px;\">\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/div>\n<div class=\"kksr-legend\" style=\"font-size: 19.2px;\"> 5\/5 &#8211; (1 vote) <\/div>\n<\/p><\/div>\n<h2 class=\"wp-block-heading\">Asyncio Overview<\/h2>\n<p><a href=\"https:\/\/realpython.com\/python-async-features\/\">Asyncio<\/a> is a Python library that allows you to write asynchronous code, providing an event loop, coroutines, and tasks to help manage concurrency without the need for parallelism.With <code>asyncio<\/code>, you can develop high-performance applications that harness the power of asynchronous programming, without running into callback hell or dealing with the complexity of threads. <\/p>\n<h2 class=\"wp-block-heading\">Async and Await Key Concepts<\/h2>\n<p class=\"has-global-color-8-background-color has-background\">By incorporating the <a href=\"https:\/\/blog.finxter.com\/python-async-await-mastering-concurrent-programming\/\"><code>async<\/code> and <code>await<\/code> keywords<\/a>, Python&#8217;s asynchronous generators build upon the foundation of traditional generators, which make use of the <a href=\"https:\/\/blog.finxter.com\/yield-keyword-in-python-a-simple-illustrated-guide\/\"><code>yield<\/code> keyword<\/a>. <\/p>\n<p>To work effectively with asyncio, there are two essential concepts you should understand: <code>async<\/code> and <code>await<\/code>.<\/p>\n<ul>\n<li><strong><code>async<\/code><\/strong>: The <code>async<\/code> keyword defines a function as a coroutine, making it possible to execute asynchronously. When you define a function with <code>async def<\/code>, you&#8217;re telling Python that the function is capable of <em>asynchronous<\/em> execution. This means that it can be scheduled to run concurrently without blocking other tasks.<\/li>\n<li><strong><code>await<\/code><\/strong>: The <code>await<\/code> keyword allows you to <em>pause and resume<\/em> the execution of a coroutine within your asynchronous code. Using <code>await<\/code> before calling another coroutine signifies that your current coroutine should <em>wait<\/em> for the completion of the called coroutine. While waiting, the <code>asyncio<\/code> event loop can perform other tasks concurrently.<\/li>\n<\/ul>\n<p>Here&#8217;s a simple example incorporating these concepts:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import asyncio async def my_coroutine(): print(\"Starting the coroutine\") # Simulate a blocking operation using asyncio.sleep await asyncio.sleep(2) print(\"Coroutine completed\") # Schedule the coroutine as a task\nmy_task = asyncio.create_task(my_coroutine()) # Run the event loop until the task is completed\nasyncio.run(my_task)\n<\/pre>\n<\/p>\n<h2 class=\"wp-block-heading\">Generators and Asyncio<\/h2>\n<p class=\"has-global-color-8-background-color has-background\">Generators are a powerful feature in Python that allow you to create an iterator using a function. They enable you to loop over a large sequence of values without creating all the values in memory. <\/p>\n<p>You can learn everything about generators in our Finxter tutorial here:<\/p>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube\"><a href=\"https:\/\/blog.finxter.com\/python-async-generator-mastering-asyncio-in-modern-applications\/\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/plugins\/wp-youtube-lyte\/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F2Ls0b1gjz2A%2Fhqdefault.jpg\" alt=\"YouTube Video\"><\/a><figcaption><\/figcaption><\/figure>\n<p class=\"has-base-2-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended<\/strong>: <a href=\"https:\/\/blog.finxter.com\/understanding-generators-in-python\/\">Understanding Generators In Python<\/a><\/p>\n<p><strong>Generators are particularly useful when working with asynchronous programming, like when using the <code>asyncio<\/code> library.<\/strong> <\/p>\n<h3 class=\"wp-block-heading\">Yield Expressions and Statements<\/h3>\n<p class=\"has-global-color-8-background-color has-background\">In Python, the <a href=\"https:\/\/blog.finxter.com\/yield-keyword-in-python-a-simple-illustrated-guide\/\"><code>yield<\/code> keyword<\/a> is used in generator functions to produce values one at a time. This enables you to pause the execution of the function, return the current value, and resume execution later. <\/p>\n<p>There are two types of <code>yield<\/code> expressions you should be familiar with: <\/p>\n<ul>\n<li>the <code>yield<\/code> expression and <\/li>\n<li>the <code>yield from<\/code> statement.<\/li>\n<\/ul>\n<p>A simple <code>yield<\/code> expression in a generator function might look like this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def simple_generator(): for i in range(5): yield i\n<\/pre>\n<p>This generator function produces values from 0 to 4, one at a time. You can use this generator in a <code>for<\/code> loop to print the generated values:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">for value in simple_generator(): print(value)\n<\/pre>\n<p class=\"has-global-color-8-background-color has-background\"><code>yield from<\/code> is a statement used to delegate part of a generator&#8217;s operation to another generator. It can simplify your code when working with nested generators.<\/p>\n<p>Here&#8217;s an example of how you might use <code>yield from<\/code> in a generator:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def nested_generator(): yield \"Start\" yield from range(3) yield \"End\" for value in nested_generator(): print(value)\n<\/pre>\n<p>This code will output:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">Start\n0\n1\n2\nEnd\n<\/pre>\n<\/p>\n<h2 class=\"wp-block-heading\">Python Async Generators<\/h2>\n<p class=\"has-global-color-8-background-color has-background\">Asynchronous generators were introduced in Python 3.6 with the <a href=\"https:\/\/peps.python.org\/pep-0525\/\">PEP 525<\/a> proposal, enabling developers to handle asynchronous tasks more efficiently using the <code>async def<\/code> and <code>yield<\/code> keywords. In an async generator, you&#8217;ll need to define a function with the <code>async def<\/code> keyword, and the function body should contain the <code>yield<\/code> statement.<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" fetchpriority=\"high\" width=\"988\" height=\"988\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/image-99.png\" alt=\"\" class=\"wp-image-1651680\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/image-99.png 988w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/image-99-300x300.png 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/image-99-150x150.png 150w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/image-99-768x768.png 768w\" sizes=\"(max-width: 988px) 100vw, 988px\" \/><\/figure>\n<\/div>\n<p>Here is an example of creating an asynchronous generator:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import asyncio async def async_generator_example(start, stop): for number in range(start, stop): await asyncio.sleep(1) yield number\n<\/pre>\n<h3 class=\"wp-block-heading\">Using Async Generators<\/h3>\n<p class=\"has-global-color-8-background-color has-background\">To consume values from an async generator, you&#8217;ll need to use the <code>async for<\/code> loop. The <code>async for<\/code> loop was introduced alongside async generators in <a href=\"https:\/\/blog.finxter.com\/how-to-check-your-python-version\/\">Python 3.6<\/a> and makes it straightforward to iterate over the yielded values from the async generator.<\/p>\n<p>Here&#8217;s an example of using <code>async for<\/code> to work with the async generator:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import asyncio async def main(): async for num in async_generator_example(1, 5): print(num) # Run the main function using asyncio's event loop\nif __name__ == \"__main__\": asyncio.run(main())\n<\/pre>\n<p>In this example, the <code>main()<\/code> function loops over the values yielded by the <code>async_generator_example()<\/code> async generator, printing them one by one.<\/p>\n<h3 class=\"wp-block-heading\">Errors in Async Generators<\/h3>\n<p class=\"has-global-color-8-background-color has-background\">Handling errors in async generators can be a bit different compared to regular generators. An important concept to understand is that when an exception occurs inside an async generator, it may propagate up the call stack and eventually reach the <code>async for<\/code> loop. To handle such situations gracefully, you should use <code>try<\/code> and <code>except<\/code> blocks within your async generator code.<\/p>\n<p>Here&#8217;s an example that shows how to handle errors in async generators:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import asyncio async def async_generator_example(start, stop): for number in range(start, stop): try: await asyncio.sleep(1) if number % 2 == 0: raise ValueError(\"Even numbers are not allowed.\") yield number except ValueError as e: print(f\"Error in generator: {e}\") async def main(): async for num in async_generator_example(1, 5): print(num) # Run the main function using asyncio's event loop\nif __name__ == \"__main__\": asyncio.run(main())\n<\/pre>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"567\" height=\"595\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/async_2222.gif\" alt=\"\" class=\"wp-image-1651682\"\/><\/figure>\n<\/div>\n<p>In this example, when the async generator encounters an even number, it raises a <code>ValueError<\/code>. The exception is handled within the generator function, allowing the async generator to continue its execution and the <code>async for<\/code> loop to iterate over the remaining odd numbers.<\/p>\n<h2 class=\"wp-block-heading\">Advanced Topics<\/h2>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"817\" height=\"817\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/Finxter_A_photorealistic_picture_of_an_25_year_old_beautiful_ko_86039034-020e-4b80-af3e-e621f62e37fb.png\" alt=\"\" class=\"wp-image-1651328\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/Finxter_A_photorealistic_picture_of_an_25_year_old_beautiful_ko_86039034-020e-4b80-af3e-e621f62e37fb.png 817w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/Finxter_A_photorealistic_picture_of_an_25_year_old_beautiful_ko_86039034-020e-4b80-af3e-e621f62e37fb-300x300.png 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/Finxter_A_photorealistic_picture_of_an_25_year_old_beautiful_ko_86039034-020e-4b80-af3e-e621f62e37fb-150x150.png 150w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/Finxter_A_photorealistic_picture_of_an_25_year_old_beautiful_ko_86039034-020e-4b80-af3e-e621f62e37fb-768x768.png 768w\" sizes=\"auto, (max-width: 817px) 100vw, 817px\" \/><\/figure>\n<\/div>\n<h3 class=\"wp-block-heading\">Multiprocessing and Threading<\/h3>\n<p>When working with Python <code>async<\/code> generators, you can leverage the power of <code>multiprocessing<\/code> and <code>threading<\/code> to execute tasks concurrently. <\/p>\n<p>The <code>concurrent.futures<\/code> module provides a high-level interface for asynchronously executing callables, enabling you to focus on your tasks rather than managing threads, processes, and synchronization.<\/p>\n<p>Using <code>ThreadPoolExecutor<\/code> and <code>ProcessPoolExecutor<\/code>, you can manage multiple threads and processes, respectively. <\/p>\n<p>For example, in asynchronous I\/O operations, you can utilize <code>asyncio<\/code> and run synchronous functions in a separate thread using the <code>run_in_executor()<\/code> method to avoid blocking the main event loop:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import asyncio\nfrom concurrent.futures import ThreadPoolExecutor async def async_fetch(url): with ThreadPoolExecutor() as executor: loop = asyncio.get_event_loop() return await loop.run_in_executor(executor, requests.get, url)\n<\/pre>\n<h3 class=\"wp-block-heading\">Contextlib and Python Asyncio<\/h3>\n<p><code>contextlib<\/code> is a useful Python library for context and resource management, and it readily integrates with <code>asyncio<\/code>. <\/p>\n<p>The <code>contextlib.asynccontextmanager<\/code> is available for creating asynchronous context managers. This can be particularly helpful when working with file I\/O, sockets, or other resources that require clean handling:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import asyncio\nfrom contextlib import asynccontextmanager @asynccontextmanager\nasync def async_open(filename, mode): file = await open_async(filename, mode) try: yield file finally: await file.close() async for line in async_open('example.txt'): print(line)\n<\/pre>\n<h3 class=\"wp-block-heading\">Asyncio and Database Operations<\/h3>\n<p>Asynchronous I\/O can significantly improve the performance of database-intensive applications. Many database libraries now support asyncio, allowing you to execute queries and manage transactions asynchronously. <\/p>\n<p>Here&#8217;s an example using the <code>aiomysql<\/code> library for interacting with a MySQL database:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import asyncio\nimport aiomysql async def query_database(query): pool = await aiomysql.create_pool(user='user', password='pass', db='mydb') async with pool.acquire() as conn: async with conn.cursor() as cur: await cur.execute(query) return await cur.fetchall()\n<\/pre>\n<h3 class=\"wp-block-heading\">Performance and Optimization Tips<\/h3>\n<p>To enhance the performance of your <code>asyncio<\/code> program, consider the following optimization tips:<\/p>\n<ul>\n<li>Profile your code to identify performance bottlenecks<\/li>\n<li>Use <code>asyncio.gather(*coroutines)<\/code> to schedule multiple coroutines concurrently, which minimizes the total execution time<\/li>\n<li>Manage the creation and destruction of tasks using <code>asyncio.create_task()<\/code> and <code>await task.cancel()<\/code><\/li>\n<li>Limit concurrency when working with resources that might become overwhelmed by too many simultaneous connections<\/li>\n<\/ul>\n<p>Keep in mind that while asyncio allows for concurrent execution of tasks, it&#8217;s not always faster than synchronous code, especially for CPU-bound operations. So, it&#8217;s essential to analyze your specific use case before deciding on an asynchronous approach.<\/p>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f9d1-200d-1f4bb.png\" alt=\"\ud83e\uddd1\u200d\ud83d\udcbb\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Tip<\/strong>: In my view, asynchronous programming doesn&#8217;t improve performance in >90% of personal and small use cases. In many professional cases it also doesn&#8217;t outperform intelligent synchronous programming due to scheduling overhead and CPU context switches.<\/p>\n<\/p>\n<h2 class=\"wp-block-heading\">Frequently Asked Questions<\/h2>\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" loading=\"lazy\" width=\"817\" height=\"817\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/Finxter_A_photorealistic_picture_of_an_25_year_old_beautiful_ko_acc9a783-7a09-48f8-8fe2-fda9bb4523a5.png\" alt=\"\" class=\"wp-image-1651332\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/Finxter_A_photorealistic_picture_of_an_25_year_old_beautiful_ko_acc9a783-7a09-48f8-8fe2-fda9bb4523a5.png 817w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/Finxter_A_photorealistic_picture_of_an_25_year_old_beautiful_ko_acc9a783-7a09-48f8-8fe2-fda9bb4523a5-300x300.png 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/Finxter_A_photorealistic_picture_of_an_25_year_old_beautiful_ko_acc9a783-7a09-48f8-8fe2-fda9bb4523a5-150x150.png 150w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/Finxter_A_photorealistic_picture_of_an_25_year_old_beautiful_ko_acc9a783-7a09-48f8-8fe2-fda9bb4523a5-768x768.png 768w\" sizes=\"auto, (max-width: 817px) 100vw, 817px\" \/><\/figure>\n<h3 class=\"wp-block-heading\">How to create an async generator in Python?<\/h3>\n<p>To create an async generator in Python, you need to define a coroutine function that utilizes the <code>yield<\/code> expression. Use the <code>async def<\/code> keyword to declare the function, and then include the <code>yield<\/code> statement to produce values. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">async def my_async_generator(): for i in range(3): await asyncio.sleep(1) yield i\n<\/pre>\n<h3 class=\"wp-block-heading\">What is the return type of an async generator?<\/h3>\n<p>The return type of an async generator is an asynchronous generator object. It&#8217;s an object that implements both <code>__aiter__<\/code> and <code>__anext__<\/code> methods, allowing you to iterate over it asynchronously using an <code>async for<\/code> loop.<\/p>\n<h3 class=\"wp-block-heading\">How to use &#8216;send&#8217; with an async generator?<\/h3>\n<p>Currently, Python does not support using <code>send<\/code> with async generators. You can only loop over the generator and make use of the <code>yield<\/code> statement.<\/p>\n<h3 class=\"wp-block-heading\">Why is an async generator not iterable?<\/h3>\n<p>An async generator is not a regular <a href=\"https:\/\/blog.finxter.com\/iterators-iterables-and-itertools\/\">iterable<\/a>, meaning you can&#8217;t use a traditional <code>for<\/code> loop due to its asynchronous nature. Instead, async generators are asynchronous iterables that must be processed using an <code>async for<\/code> loop.<\/p>\n<h3 class=\"wp-block-heading\">How to work with an async iterator?<\/h3>\n<p>To work with an async iterator, use an <code>async for<\/code> loop. This will allow you to iterate through the asynchronous generator and process its items concurrently. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">async def my_async_generator_consumer(): async for value in my_async_generator(): print(\"Received:\", value)\n<\/pre>\n<h3 class=\"wp-block-heading\">Can I use &#8216;yield from&#8217; with an async generator?<\/h3>\n<p>No, you cannot use <code>yield from<\/code> with an async generator. Instead, you should use the <code>async for<\/code> loop to asynchronously iterate through one generator and then yield the values inside another async generator. For instance:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">async def another_async_generator(): async for item in my_async_generator(): yield item\n<\/pre>\n<\/p>\n<p>This <code>another_async_generator()<\/code> function will asynchronously iterate over <code>my_async_generator()<\/code> and yield items produced by the original generator.<\/p>\n<p>That&#8217;s enough for today. Let&#8217;s have some fun &#8212; check out this blog tutorial on creating a small fun game in Python:<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><a href=\"https:\/\/blog.finxter.com\/robotaxi-tycoon-scale-your-fleet-to-1m-a-python-mini-game-made-by-chatgpt\/\" target=\"_blank\" rel=\"noreferrer noopener\"><img decoding=\"async\" loading=\"lazy\" width=\"993\" height=\"823\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/09\/robotaxi-1.gif\" alt=\"\" class=\"wp-image-1651683\"\/><\/a><\/figure>\n<\/div>\n<p class=\"has-base-2-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended<\/strong>: <a href=\"https:\/\/blog.finxter.com\/robotaxi-tycoon-scale-your-fleet-to-1m-a-python-mini-game-made-by-chatgpt\/\">Robotaxi Tycoon \u2013 Scale Your Fleet to $1M! A Python Mini Game Made By ChatGPT<\/a><\/p>\n<p>The post <a rel=\"nofollow\" href=\"https:\/\/blog.finxter.com\/python-async-generator-mastering-asyncio-in-modern-applications\/\">Python Async Generator: Mastering Asyncio in Modern Applications<\/a> appeared first on <a rel=\"nofollow\" href=\"https:\/\/blog.finxter.com\">Be on the Right Side of Change<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>5\/5 &#8211; (1 vote) Asyncio Overview Asyncio is a Python library that allows you to write asynchronous code, providing an event loop, coroutines, and tasks to help manage concurrency without the need for parallelism.With asyncio, you can develop high-performance applications that harness the power of asynchronous programming, without running into callback hell or dealing with [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-134869","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/134869","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=134869"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/134869\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=134869"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=134869"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=134869"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}