<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>async Archives - Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/category/async/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com/category/async/</link>
	<description></description>
	<lastBuildDate>Sat, 23 Sep 2023 06:52:54 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://blog.finxter.com/wp-content/uploads/2020/08/cropped-cropped-finxter_nobackground-32x32.png</url>
	<title>async Archives - Be on the Right Side of Change</title>
	<link>https://blog.finxter.com/category/async/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Python Async IO &#8211; The Ultimate Guide in a Single Post</title>
		<link>https://blog.finxter.com/python-async-io-the-ultimate-guide-in-a-single-post/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Sat, 23 Sep 2023 06:50:42 +0000</pubDate>
				<category><![CDATA[async]]></category>
		<category><![CDATA[Distributed Systems]]></category>
		<category><![CDATA[Parallel Programming]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1651739</guid>

					<description><![CDATA[<p>As a Python developer, you might have come across the concept of asynchronous programming. Asynchronous programming, or async I/O, is a concurrent programming design that has received dedicated support in Python, evolving rapidly from Python 3.4 through 3.7 and beyond. With async I/O, you can manage multiple tasks concurrently without the complexities of parallel programming, ... <a title="Python Async IO &#8211; The Ultimate Guide in a Single Post" class="read-more" href="https://blog.finxter.com/python-async-io-the-ultimate-guide-in-a-single-post/" aria-label="Read more about Python Async IO &#8211; The Ultimate Guide in a Single Post">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/python-async-io-the-ultimate-guide-in-a-single-post/">Python Async IO &#8211; The Ultimate Guide in a Single Post</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>As a Python developer, you might have come across the concept of asynchronous programming. Asynchronous programming, or async I/O, is a concurrent programming design that has received dedicated support in Python, evolving rapidly from <a href="https://blog.finxter.com/how-to-check-your-python-version/">Python 3.4 through 3.7</a> and beyond. With async I/O, you can manage multiple tasks concurrently without the complexities of parallel programming, making it a perfect fit for I/O bound and high-level structured network code.</p>



<p>In the Python world, the <code><a href="https://blog.finxter.com/how-to-check-asyncio-package-version-in-python/">asyncio</a></code> library is your go-to tool for implementing asynchronous I/O. This library provides various <strong>high-level APIs to run Python coroutines concurrently, giving you full control over their execution</strong>. It also enables you to perform network I/O, Inter-process Communication (IPC), control subprocesses, and synchronize concurrent code using tasks and queues.</p>



<h2 class="wp-block-heading">Understanding Asyncio</h2>



<p>In the world of Python programming, <strong>asyncio</strong> plays a crucial role in designing efficient and concurrent code without using threads. It is a library that helps you manage tasks, event loops, and coroutines. To fully benefit from <code>asyncio</code>, you must understand some key components.</p>



<p>First, let&#8217;s start with <strong>coroutines</strong>. They are special functions that can pause their execution at specified points without completely terminating it. In Python, you declare a coroutine using the <code>async def</code> syntax. </p>



<p>For instance:</p>



<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_coroutine():
    # Your code here
</pre>



<p>Next, the <strong>event loop</strong> is a core feature of asyncio and is responsible for executing tasks concurrently and managing I/O operations. An event loop runs tasks one after the other and can pause a task when it is waiting for external input, such as reading data from a file or from the network. It also listens for other tasks that are ready to run, switches to them, and resumes the initial task when it receives the input.</p>



<p><strong>Tasks</strong> are the coroutines wrapped in an object, managed by the event loop. They are used to run multiple concurrent coroutines simultaneously. You can create a task using the <code>asyncio.create_task()</code> function, like this:</p>



<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_coroutine():
    # Your code here

task = asyncio.create_task(my_coroutine())
</pre>



<p>Finally, the <code>sleep</code> function in asyncio is used to simulate I/O bound tasks or a delay in the code execution. It works differently than the standard <code>time.sleep()</code> function as it is non-blocking and allows other coroutines to run while one is paused. You can use <code>await asyncio.sleep(delay)</code> to add a brief pause in your coroutine execution.</p>



<p>Putting it all together, you can use <code>asyncio</code> to efficiently manage multiple coroutines concurrently:</p>



<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 task_one():
    print('Starting task one')
    await asyncio.sleep(3)
    print('Finished task one')

async def task_two():
    print('Starting task two')
    await asyncio.sleep(1)
    print('Finished task two')

async def main():
    task1 = asyncio.create_task(task_one())
    task2 = asyncio.create_task(task_two())

    await task1
    await task2

# Run the event loop
asyncio.run(main())
</pre>



<p>In this example, the event loop will start running both tasks concurrently, allowing task two to complete while task one is paused during the sleep period. This allows you to handle multiple tasks in a single-threaded environment. </p>



<p>You can see it play out in this Gif:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img fetchpriority="high" decoding="async" width="568" height="598" src="https://blog.finxter.com/wp-content/uploads/2023/09/asynch9999.gif" alt="" class="wp-image-1651747"/></figure>
</div>


<h2 class="wp-block-heading">Async/Await Syntax</h2>



<p>In Python, the <a href="https://blog.finxter.com/python-async-await-mastering-concurrent-programming/">async/await</a> syntax is a powerful tool to create and manage asynchronous tasks without getting lost in callback hell or making your code overly complex.</p>



<p>The async/await keywords are at the core of asynchronous code in Python. You can use the <code>async def</code> keyword to define an asynchronous function. Inside this function, you can use the <code>await</code> keyword to pause the execution of the function until some asynchronous operation is finished. </p>



<p>For example:</p>



<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():
    print("Start")
    await asyncio.sleep(2)
    print("End")
</pre>



<p><a href="https://blog.finxter.com/python-async-generator-mastering-asyncio-in-modern-applications/"><code>yield</code> and <code>yield from</code></a> are related to asynchronous code in the context of generators, which provide a way to iterate through a collection of items without loading all of them into memory at once. In Python 3.3 and earlier, <code>yield from</code> was used to delegate a part of a generator&#8217;s operation to another generator. However, in later versions of Python, the focus shifted to async/await for managing asynchronous tasks, and <code>yield from</code> became less commonly used.</p>



<p>For example, before Python 3.4, you might have used a generator with <code>yield</code> and <code>yield from</code> like this:</p>



<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 generator_a():
    for i in range(3):
        yield i

def generator_b():
    yield from generator_a()

for item in generator_b():
    print(item)
</pre>



<p>With the introduction of async/await, asynchronous tasks can be written more consistently and readably. You can convert the previous example to use async/await as follows:</p>



<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_a():
    for i in range(3):
        yield i
        await asyncio.sleep(1)

async def async_generator_b():
    async for item in async_generator_a():
        print(item)

await async_generator_b()
</pre>



<p></p>



<h2 class="wp-block-heading">Working with Tasks and Events</h2>



<p>In asynchronous programming with Python, you&#8217;ll often work with tasks and events to manage the execution of simultaneous IO-bound operations. To get started with this model, you&#8217;ll need to understand the <strong>event loop</strong> and the concept of <strong>tasks</strong>.</p>



<p>The event loop is a core component of Python&#8217;s <code>asyncio</code> module. It&#8217;s responsible for managing and scheduling the execution of tasks. A task, created using <code>asyncio.create_task()</code>, represents a coroutine that runs independently of other tasks in the same event loop.</p>



<p>To create tasks, first, define an asynchronous function using the <code>async def</code> syntax. Then, you can use the <code><a href="https://blog.finxter.com/python-async-await-mastering-concurrent-programming/">await</a></code> keyword to make non-blocking calls within this function. The <code>await</code> keyword allows the event loop to perform other tasks while waiting for an asynchronous operation to complete. </p>



<p>Here&#8217;s an example:</p>



<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_async_function():
    print("Task started")
    await asyncio.sleep(2)
    print("Task finished")

event_loop = asyncio.get_event_loop()
task = event_loop.create_task(my_async_function())
event_loop.run_until_complete(task)
</pre>



<p>In this example, <code>my_async_function</code> is an asynchronous function, and <code>await asyncio.sleep(2)</code> represents an asynchronous operation. The <code>event_loop.create_task()</code> method wraps the coroutine into a task, allowing it to run concurrently within the event loop.</p>



<p>To execute tasks and manage their output, you can use <code>asyncio.gather()</code>. This function receives a list of tasks and returns their outputs as a list in the same order they were provided. Here&#8217;s an example of how you can use <code>asyncio.gather()</code>:</p>



<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_task_1():
    await asyncio.sleep(1)
    return "Task 1 completed"

async def async_task_2():
    await asyncio.sleep(2)
    return "Task 2 completed"

async def main():
    tasks = [async_task_1(), async_task_2()]
    results = await asyncio.gather(*tasks)
    print(results)

asyncio.run(main())
</pre>



<p>In this example, <code>asyncio.gather()</code> awaits the completion of both tasks and then collects their output in a list, which is printed at the end.</p>



<p>Working with tasks and events in Python&#8217;s asynchronous IO model helps improve the efficiency of your code when dealing with multiple IO operations, ensuring smoother and faster execution. Remember to use <code>asyncio.create_task()</code>, <code>await</code>, and <code>asyncio.gather()</code> when handling tasks within your event loop.</p>



<h2 class="wp-block-heading">Coroutines and Futures</h2>



<p>In Python, async IO is powered by coroutines and futures. <strong>Coroutines</strong> are functions that can be paused and resumed at specific points, allowing other tasks to run concurrently. They are declared with the <code>async</code> keyword and used with <code>await</code>. <a href="https://docs.python.org/3/library/asyncio-task.html">Asyncio coroutines</a> are the preferred way to write asynchronous code in Python.</p>



<p>On the other hand, <strong>futures</strong> represent the result of an asynchronous operation that hasn&#8217;t completed yet. They are primarily used for interoperability between callback-based code and the async/await syntax. With asyncio, <a href="https://docs.python.org/3/library/asyncio-future.html">Future objects</a> should be created using <code>loop.create_future()</code>.</p>



<p>To execute multiple coroutines concurrently, you can use the <a href="https://stackoverflow.com/questions/32054066/how-to-run-multiple-coroutines-concurrently-using-asyncio"><code>gather</code></a> function. <code>asyncio.gather()</code> is a high-level function that takes one or more awaitable objects (coroutines or futures) and schedules them to run concurrently. Here&#8217;s an example:</p>



<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 foo():
    await asyncio.sleep(1)
    return "Foo"

async def bar():
    await asyncio.sleep(2)
    return "Bar"

async def main():
    results = await asyncio.gather(foo(), bar())
    print(results)

asyncio.run(main())
</pre>



<p>In this example, both <code>foo()</code> and <code>bar()</code> coroutines run concurrently, and the <code>gather()</code> function returns a list of their results.</p>



<p>Error handling in asyncio is done through the <code>set_exception()</code> method. If a coroutine raises an exception, you can catch the exception and attach it to the associated future using <a href="https://docs.python.org/3/library/asyncio-future.html#asyncio.Future.set_exception"><code>future.set_exception()</code></a>. This allows other coroutines waiting for the same future to handle the exception gracefully.</p>



<p>In summary, working with coroutines and futures helps you write efficient, asynchronous code in Python. Use coroutines along with the async/await syntax for defining asynchronous tasks, and futures for interacting with low-level callback-based code. Utilize functions like <code>gather()</code> for running multiple coroutines concurrently, and handle errors effectively with <code>future.set_exception()</code>.</p>



<h2 class="wp-block-heading">Threading and Multiprocessing</h2>



<p>In the world of Python, you have multiple options for concurrent execution and managing concurrency. Two popular approaches to achieve this are <strong>threading</strong> and <strong>multiprocessing</strong>.</p>



<p><strong>Threading</strong> can be useful when you want to improve the performance of your program by efficiently utilizing your CPU&#8217;s time. It allows you to execute multiple threads in parallel within a single process. Threads share memory and resources, which makes them lightweight and more suitable for I/O-bound tasks. However, because of the Global Interpreter Lock (GIL) in Python, only one thread can execute at a time, limiting the benefits of threading for CPU-bound tasks. You can explore the <code>threading</code> module for building multithreaded applications.</p>



<p><strong>Multiprocessing</strong> overcomes the limitations of threading by using multiple processes working independently. Each process has its own Python interpreter, memory space, and resources, effectively bypassing the GIL. This approach is better for CPU-bound tasks, as it allows you to utilize multiple cores to achieve true parallelism. To work with multiprocessing, you can use Python&#8217;s <code>multiprocessing</code> module.</p>



<p>While both threading and multiprocessing help manage concurrency, it is essential to choose the right approach based on your application&#8217;s requirements. Threading is more suitable when your tasks are I/O-bound, and multiprocessing is advisable for CPU-bound tasks. When dealing with a mix of I/O-bound and CPU-bound tasks, using a combination of the two might be beneficial.</p>



<p>Async I/O offers another approach for handling concurrency and might be a better fit in some situations. However, understanding threading and multiprocessing remains crucial to make informed decisions and efficiently handle concurrent execution in Python.</p>



<h2 class="wp-block-heading">Understanding Loops and Signals</h2>



<p>In the world of Python async IO, working with loops and signals is an essential skill to grasp. As a developer, you must be familiar with these concepts to harness the power of asynchronous programming.</p>



<p>Event loops are at the core of asynchronous programming in Python. They provide a foundation for scheduling and executing tasks concurrently. The <code>asyncio</code> library helps you create and manage these event loops. You can experiment with event loops using Python&#8217;s <code>asyncio</code> REPL, which can be started by running <code>python -m asyncio</code> in your command line.</p>



<p>Signals, on the other hand, are a way for your program to receive notifications about certain events, like a user interrupting the execution of the program. A common use case for handling signals in asynchronous programming involves stopping the event loop gracefully when it receives a termination signal like <code>SIGINT</code> or <code>SIGTERM</code>.</p>



<p>A useful method for running synchronous or blocking functions in an asynchronous context is the <code>loop.run_in_executor()</code> method. This allows you to offload the execution of such functions to a separate thread or process, preventing them from blocking the event loop. For example, if you have a CPU-bound operation that cannot be implemented using <code>asyncio</code>&#8216;s native coroutines, you can utilize <code>loop.run_in_executor()</code> to keep the event loop responsive.</p>



<p>Here&#8217;s a simple outline of using loops and signals together in your asynchronous Python code:</p>



<ol class="wp-block-list">
<li>Create an event loop using <code>asyncio.get_event_loop()</code>.</li>



<li>Register your signal handlers with the event loop, typically by using the <code>loop.add_signal_handler()</code> method.</li>



<li>Schedule your asynchronous tasks and coroutines in the event loop.</li>



<li>Run the event loop using <code>loop.run_forever()</code>, which will keep running until you interrupt it with a signal or a coroutine stops it explicitly.</li>
</ol>



<p></p>



<h2 class="wp-block-heading">Managing I/O Operations</h2>



<p>When working with I/O-bound tasks in Python, it&#8217;s essential to manage I/O operations efficiently. Using <strong>asyncio</strong> can help you handle these tasks concurrently, resulting in more performant and scalable code.</p>



<p>I/O-bound tasks are operations where the primary bottleneck is fetching data from input/output sources like files, network requests, or databases. To improve the performance of your I/O-bound tasks, you can use asynchronous programming techniques. In Python, this often involves using the <strong>asyncio</strong> library and writing non-blocking code.</p>



<p>Typically, you&#8217;d use blocking code for I/O operations, which means waiting for the completion of an I/O task before continuing with the rest of the code execution. This blocking behavior can lead to inefficient use of resources and poor performance, especially in larger programs with multiple I/O-bound tasks.</p>



<p>Non-blocking code, on the other hand, allows your program to continue executing other tasks while waiting for the I/O operation to complete. This can significantly improve the efficiency and performance of your program. When using Python&#8217;s <strong>asyncio</strong> library, you write non-blocking code with <strong>coroutines</strong>.</p>



<p>For I/O-bound tasks involving file operations, you can use libraries like <strong>aiofiles</strong> to perform asynchronous file I/O. Just like with asyncio, aiofiles provides an API to work with files using non-blocking code, improving the performance of your file-based tasks.</p>



<p>When dealing with network I/O, the <strong><code>asyncio</code></strong> library provides APIs to perform tasks such as asynchronous reading and writing operations for sockets and other resources. This enables you to manage multiple network connections concurrently, efficiently utilizing your system resources.</p>



<p>In summary, when managing I/O operations in Python:</p>



<ul class="wp-block-list">
<li>Identify I/O-bound tasks in your program</li>



<li>Utilize the <strong>asyncio</strong> library to write non-blocking code using coroutines</li>



<li>Consider using <strong>aiofiles</strong> for asynchronous file I/O</li>



<li>Utilize asyncio APIs to manage network I/O efficiently</li>
</ul>



<p></p>



<h2 class="wp-block-heading">Handling Transports and Timeouts</h2>



<p>When working with Python&#8217;s Async IO, you might need to handle transports and timeouts effectively. Transports and protocols are low-level event loop APIs for implementing network or IPC protocols such as HTTP. They help improve the performance of your application by using callback-based programming style. You can find more details in the <a href="https://docs.python.org/3/library/asyncio-protocol.html">Python 3.11.4 documentation</a>.</p>



<p>Timeouts are often useful when you want to prevent your application from waiting indefinitely for a task to complete. To handle timeouts in asyncio, you can use the <code>asyncio.wait_for</code> function. This allows you to set a maximum time that your function can run. If the function doesn&#8217;t complete within the specified time, an <code>asyncio.TimeoutError</code> is raised.</p>



<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 some_function():
    await asyncio.sleep(5)

async def main():
    try:
        await asyncio.wait_for(some_function(), timeout=3)
    except asyncio.TimeoutError:
        print("Task took too long.")

asyncio.run(main())
</pre>



<p>In this example, <code>some_function</code> takes 5 seconds to complete, but we set a timeout of 3 seconds. As a result, an <code>asyncio.TimeoutError</code> is raised, and the program prints &#8220;Task took too long.&#8221;</p>



<p class="has-global-color-8-background-color has-background">Another concept to be familiar with is the executor, which allows you to run synchronous functions in an asynchronous context. You can use the <code>loop.run_in_executor()</code> method, where <code>loop</code> is an instance of the event loop. This method takes three arguments: the executor, the function you want to run, and any arguments for that function. The executor can be a custom one or <code>None</code> for the default <code>ThreadPoolExecutor</code>. </p>



<p>Here&#8217;s an example:</p>



<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
import time

def sync_function(seconds):
    time.sleep(seconds)
    return "Slept for {} seconds".format(seconds)

async def main():
    loop = asyncio.get_event_loop()
    result = await loop.run_in_executor(None, sync_function, 3)
    print(result)

asyncio.run(main())
</pre>



<p>In this example, we run the synchronous <code>sync_function</code> inside the async <code>main()</code> function using the <code>loop.run_in_executor()</code> method.</p>



<p></p>



<h2 class="wp-block-heading">Dealing with Logging and Debugging</h2>



<p>When working with Python&#8217;s <code>asyncio</code> library, properly handling logging and debugging is essential for ensuring efficient and smooth development. As a developer, it&#8217;s crucial to stay confident and knowledgeable when dealing with these tasks.</p>



<p>To begin logging in your asynchronous Python code, you need to initialize a logger object. Import the <code>logging</code> module and create an instance of the <code>Logger</code> class, like this:</p>



<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 logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
</pre>



<p>This configuration sets up a logger object that will capture debug-level log messages. To log a message, simply call the appropriate method like <code>logger.debug</code>, <code>logger.info</code>, or <code>logger.error</code>:</p>



<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_function():
    logger.debug("Debug message")
    logger.info("Info message")
    logger.error("Error message")
    await some_async_operation()
</pre>



<p>Keep in mind that Python&#8217;s logging module is not inherently asynchronous. However, there are ways to work around this issue. One approach is to use a <a href="https://stackoverflow.com/questions/45842926/python-asynchronous-logging"><code>ThreadPoolExecutor</code></a>, which executes logging methods in a separate thread:</p>



<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 concurrent.futures
import logging

executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)

def log_info(msg, *args):
    executor.submit(logging.info, msg, *args)

async def my_async_function():
    log_info("Info message")
    await some_async_operation()
</pre>



<p>For debugging your asynchronous code, it&#8217;s possible to enable the debug mode in asyncio by calling the <code>loop.set_debug()</code> method. Additionally, consider setting the log level of the <code>asyncio</code> logger to <code>logging.DEBUG</code> and configuring the <code>warnings</code> module to display <code>ResourceWarning</code> warnings. Check the <a href="https://docs.python.org/3/library/asyncio-dev.html">official Python documentation</a> for more information and best practices.</p>



<p></p>



<h2 class="wp-block-heading">Understanding Virtual Environments and Resources</h2>



<p>When working with Python, you&#8217;ll often encounter the need for a <strong>virtual environment</strong>. A virtual environment is an isolated environment for your Python applications, which allows you to manage resources and dependencies efficiently. It helps ensure that different projects on your computer do not interfere with each other in terms of dependencies and versions, maintaining the availability of the required resources for each project.</p>



<p>To create a virtual environment, you can use built-in Python libraries such as <code>venv</code> or third-party tools like <code>conda</code>. Once created, you&#8217;ll activate the virtual environment and install the necessary packages needed for your project. This ensures that the resources are available for your application without causing conflicts with other Python packages or applications on your computer. </p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f517.png" alt="🔗" class="wp-smiley" style="height: 1em; max-height: 1em;" /> For a more detailed explanation of virtual environments, check out this <a href="https://www.dataquest.io/blog/a-complete-guide-to-python-virtual-environments/">complete guide to Python virtual environments</a>.</p>



<p>When working with async IO in Python, it&#8217;s crucial to manage resources effectively, especially when dealing with asynchronous operations like networking requests or file I/O. By using a virtual environment, you can make sure that your project has the correct version of <code>asyncio</code> and other async libraries, ensuring that your code runs smoothly and efficiently.</p>



<p>In a virtual environment, resources are allocated based, on the packages and libraries you install. This way, only the necessary resources for your project are used, improving performance and consistency across development. The virtual environment lets you keep track of your project&#8217;s dependencies, making it easier to maintain and share your project with others, ensuring that they can access the required resources without compatibility issues.</p>



<p></p>



<h2 class="wp-block-heading">Optimizing Asynchronous Program</h2>



<p>When working with Python, you may often encounter situations where an asynchronous program can significantly improve the performance and responsiveness of your application. This is especially true when dealing with I/O-bound tasks or high-level structured network code, where <a href="https://docs.python.org/3/library/asyncio.html"><code>asyncio</code></a> can be your go-to library for writing concurrent code.</p>



<p>Before diving into optimization techniques, it&#8217;s crucial to understand the difference between synchronous and asynchronous programs. In a synchronous program, tasks are executed sequentially, blocking other tasks from running. Conversely, an asynchronous program allows you to perform multiple tasks concurrently without waiting for one to complete before starting another. This cooperative multitasking approach enables your asynchronous program to run much faster and more efficiently.</p>



<p>To make the most of your asynchronous program, consider applying the following techniques:</p>



<ol class="wp-block-list">
<li><strong>Use async/await syntax</strong>: Employing the <code>async</code> and <code>await</code> keywords when defining asynchronous functions and awaiting their results ensures proper execution and responsiveness.</li>



<li><strong>Implement an event loop</strong>: The event loop is the core of an asyncio-based application. It schedules, executes, and manages tasks within the program, so it&#8217;s crucial to utilize one effectively.</li>



<li><strong>Leverage libraries</strong>: Many asynchronous frameworks, such as web servers and database connection libraries, have been built on top of asyncio. Take advantage of these libraries to simplify and optimize your asynchronous program.</li>



<li><strong>Avoid blocking code</strong>: Blocking code can slow down the execution of your asynchronous program. Ensure your program is entirely non-blocking by avoiding time-consuming operations or synchronous APIs.</li>
</ol>



<p>It&#8217;s essential to remember that while asynchronous programming has its advantages, it might not always be the best solution. In situations where your tasks are CPU-bound or require a more straightforward processing flow, a synchronous program might be more suitable.</p>



<h2 class="wp-block-heading">Exploring Asyncio Libraries and APIs</h2>



<p>When working with asynchronous programming in Python, it&#8217;s essential to explore the available libraries you can use. One such library is <strong>aiohttp</strong>. It allows you to make asynchronous HTTP requests efficiently using <code>asyncio</code>. You can find more details about this library from the <a href="https://aiohttp.readthedocs.io/en/stable/"><code>aiohttp</code> documentation</a>.</p>



<p>To get started with <code>aiohttp</code>, you&#8217;ll first need to install the library:</p>



<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="">pip install aiohttp
</pre>



<p>In your Python code, you can now import <code>aiohttp</code> and use it with the <code>asyncio</code> library. For example, if you want to make an asynchronous GET request, you can use the following code:</p>



<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 aiohttp
import asyncio

async def fetch_data(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

async def main():
    url = 'https://api.example.com/data'
    data = await fetch_data(url)
    print(data)

await main()
</pre>



<p>In the example above, the <code>fetch_data</code> function is defined as an async function using the <code>async def</code> syntax. This indicates that this function can be called with the <code>await</code> statement within other asynchronous functions.</p>



<p>The <code>pathlib</code> library provides classes for working with filesystem paths. While it is not directly related to async IO, it can be useful when working with file paths in your async projects. The <code>pathlib.Path</code> class offers a more Pythonic way to handle file system paths, making it easier to manipulate file and directory paths across different operating systems. You can read more about this library in the <a href="https://docs.python.org/3/library/pathlib.html">official Python documentation on <code>pathlib</code></a>.</p>



<p>When you create <a href="https://blog.finxter.com/python-async-function/">async function</a> calls in your code, remember to use the <code>await</code> keyword when calling them. This ensures that the function is executed asynchronously. By combining the power of <code>aiohttp</code>, <code>asyncio</code>, and other async-compatible libraries, you can efficiently perform multiple tasks concurrently in your Python projects.</p>



<p></p>



<h2 class="wp-block-heading">Understanding Queues and Terminals</h2>



<p>With Python&#8217;s <code>asyncio</code> module, you can write concurrent, asynchronous code that works efficiently on I/O-bound tasks and network connections. In this context, <a href="https://docs.python.org/3/library/asyncio-queue.html">queues</a> become helpful tools for coordinating the execution of multiple tasks and managing shared resources.</p>



<p>Queues in <code>asyncio</code> are similar to standard Python queues, but they have special asynchronous properties. With coroutine functions such as <code>get()</code> and <code>put()</code>, you can efficiently retrieve an item from the queue or insert an item, respectively. When the queue is empty, the <code>get()</code> function will wait until an item becomes available. This enables smooth flow control and ensures that your async tasks are executed in the most optimal order.</p>



<p>Terminals, on the other hand, are interfaces for interacting with your system &#8211; either through command-line or graphical user interfaces. When working with async tasks in Python, terminals play a crucial role in tracking the progress and execution of your tasks. You can use terminals to initiate and monitor the state of your async tasks by entering commands and viewing the output.</p>



<p>When it comes to incorporating multithreaded or asynchronous programming in a parent-child relationship, queues and terminals can come in handy. Consider a scenario where a parent task is responsible for launching multiple child tasks that operate concurrently. In this case, a queue can facilitate the communication and synchronization between parent and child tasks by efficiently passing data to and fro.</p>



<p>Here are a few tips to keep in mind while working with queues and terminals in asynchronous Python programming:</p>



<ul class="wp-block-list">
<li>Use <code>asyncio.Queue()</code> to create an instance suitable for async tasks, while still maintaining similar functionality as a standard Python queue.</li>



<li>For managing timeouts, remember to use the <code>asyncio.wait_for()</code> function in conjunction with queue operations, since the methods of <code>asyncio</code> queues don&#8217;t have a built-in timeout parameter.</li>



<li>When working with terminals, be mindful of potential concurrency issues. Make sure you avoid race conditions by properly synchronizing your async tasks&#8217; execution using queues, locks, and other synchronization primitives provided by the <code>asyncio</code> module.</li>
</ul>



<p></p>



<h2 class="wp-block-heading">Frequently Asked Questions</h2>



<h3 class="wp-block-heading">How does asyncio compare to threading in Python?</h3>



<p>Asyncio is a concurrency model that uses a single thread and an event loop to execute tasks concurrently. While threading allows for concurrent execution of tasks using multiple threads, asyncio provides better performance by managing tasks in a non-blocking manner within a single thread. Thus, asyncio is often preferred when dealing with I/O-bound tasks, as it can handle many tasks without creating additional threads.</p>



<h3 class="wp-block-heading">What are the main components of the asyncio event loop?</h3>



<p>The asyncio event loop is responsible for managing asynchronous tasks in Python. Its main components include:</p>



<ol class="wp-block-list">
<li>Scheduling tasks: The event loop receives and schedules coroutine functions for execution.</li>



<li>Managing I/O operations: The event loop monitors I/O operations and receives notifications when the operations are complete.</li>



<li>Executing asynchronous tasks: The event loop executes scheduled tasks in a non-blocking manner, allowing other tasks to run concurrently.</li>
</ol>



<h3 class="wp-block-heading">How do I use asyncio with pip?</h3>



<p>To use asyncio in your Python projects, no additional installation is needed, as it is included in the Python Standard Library from Python version 3.4 onwards. Simply import asyncio in your Python code and make use of its features.</p>



<h3 class="wp-block-heading">What is the difference between asyncio.run() and run_until_complete()?</h3>



<p><code>asyncio.run()</code> is a newer and more convenient function for running an asynchronous coroutine until it completes. It creates an event loop, runs the passed coroutine, and closes the event loop when the task is finished. <code>run_until_complete()</code> is an older method that requires an existing event loop object on which to run a coroutine.</p>



<p>Here&#8217;s an example of how to use <code>asyncio.run()</code>:</p>



<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 example_coroutine():
    await asyncio.sleep(1)
    print("Coroutine has completed")

asyncio.run(example_coroutine())
</pre>



<h3 class="wp-block-heading">How can I resolve the &#8216;asyncio.run() cannot be called from a running event loop&#8217; error?</h3>



<p>This error occurs when you try to call <code>asyncio.run()</code> inside an already running event loop. Instead of using <code>asyncio.run()</code> in this case, you should use <code>create_task()</code> or <code>gather()</code> functions to schedule your coroutines to run concurrently within the existing loop.</p>



<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 example_coroutine():
    await asyncio.sleep(1)
    print("Coroutine has completed")

async def main():
    task = asyncio.create_task(example_coroutine())
    await task

asyncio.run(main())
</pre>



<h3 class="wp-block-heading">Can you provide an example of using async/await in Python?</h3>



<p>Here&#8217;s a simple example demonstrating the use of async/await in Python:</p>



<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_function():
    print("Function starting")
    await asyncio.sleep(2)
    print("Function completed")

async def main():
    await asyncio.gather(async_function(), async_function())

asyncio.run(main())
</pre>



<p>This example demonstrates two async functions running concurrently. The <code>main()</code> function uses <code>asyncio.gather()</code> to run both <code>async_function()</code> tasks at the same time, and <code>asyncio.run(main())</code> starts the event loop to execute them.</p>



<figure class="wp-block-image size-large"><a href="https://blog.finxter.com/how-to-request-openais-api-asynchronously-in-python/" target="_blank" rel="noreferrer noopener"><img decoding="async" width="1024" height="572" src="https://blog.finxter.com/wp-content/uploads/2023/09/image-102-1-1024x572.png" alt="" class="wp-image-1651742" srcset="https://blog.finxter.com/wp-content/uploads/2023/09/image-102-1-1024x572.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/09/image-102-1-300x168.png 300w, https://blog.finxter.com/wp-content/uploads/2023/09/image-102-1-768x429.png 768w, https://blog.finxter.com/wp-content/uploads/2023/09/image-102-1.png 1254w" sizes="(max-width: 1024px) 100vw, 1024px" /></a></figure>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/26a1.png" alt="⚡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/how-to-request-openais-api-asynchronously-in-python/">Can I Run OpenAI’s API in Parallel? Yes, with Python Async!</a></p>
<p>The post <a href="https://blog.finxter.com/python-async-io-the-ultimate-guide-in-a-single-post/">Python Async IO &#8211; The Ultimate Guide in a Single Post</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python Async Lambda: Exploring its Applications and Usage</title>
		<link>https://blog.finxter.com/python-async-lambda-exploring-its-applications-and-usage/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Fri, 22 Sep 2023 20:16:50 +0000</pubDate>
				<category><![CDATA[async]]></category>
		<category><![CDATA[Distributed Systems]]></category>
		<category><![CDATA[Parallel Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Built-in Functions]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1651727</guid>

					<description><![CDATA[<p>As a Python developer, you might be familiar with lambda functions, which provide a simple and concise way to create anonymous functions. However, when it comes to asynchronous programming, you may wonder if it is possible to use async and await within lambda functions to create &#8220;async lambdas.&#8221; Currently, Python does not natively support async ... <a title="Python Async Lambda: Exploring its Applications and Usage" class="read-more" href="https://blog.finxter.com/python-async-lambda-exploring-its-applications-and-usage/" aria-label="Read more about Python Async Lambda: Exploring its Applications and Usage">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/python-async-lambda-exploring-its-applications-and-usage/">Python Async Lambda: Exploring its Applications and Usage</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>As a Python developer, you might be familiar with <a href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/">lambda functions</a>, which provide a simple and concise way to create anonymous functions. However, when it comes to asynchronous programming, you may wonder if it is possible to use async and await within lambda functions to create <strong><em>&#8220;async lambdas.&#8221;</em></strong></p>



<p><strong>Currently, Python does not natively support async lambda functions. </strong>This limitation is due to the language design, as the <a href="https://blog.finxter.com/python-async-await-mastering-concurrent-programming/"><code>async</code> and <code>await</code></a> keywords are reserved for coroutines and cannot be used directly within a lambda function. Asynchronous programming in Python relies on the async/await syntax for non-blocking execution, typically used in more sophisticated functions instead of simple, <a href="https://blog.finxter.com/python-return-lambda-from-function/">one-liner lambdas</a>.</p>



<p>Although async lambdas are not supported out-of-the-box, workarounds exist for specific use cases, such as using the <code><a href="https://blog.finxter.com/how-to-check-asyncio-package-version-in-python/">asyncio</a></code> module and leveraging higher-order async functions. <strong>However, these techniques may potentially increase code complexity and decrease readability.</strong> </p>



<h2 class="wp-block-heading">Understanding Async Lambda</h2>



<h3 class="wp-block-heading">Asynchronous Programming in Python</h3>



<p>Asynchronous programming in Python enables you to write more efficient code by allowing multiple tasks to run concurrently without waiting for one task to complete before starting another. </p>



<p>This approach helps improve the performance of your applications, especially when dealing with I/O-bound tasks, as it prevents your code from being blocked by such operations.</p>



<p>In the world of Python, <code>async/await</code> keywords are commonly used for asynchronous programming. They work together to create and handle asynchronous code, providing a better way to manage concurrency in your program.</p>



<h3 class="wp-block-heading">Async/Await Syntax</h3>



<p class="has-global-color-8-background-color has-background">The <code>async</code> keyword is used to declare a function as asynchronous, meaning that it will return a coroutine object when called. This coroutine object won&#8217;t execute immediately; instead, it requires you to use the <code>await</code> keyword to execute it.</p>



<p>Here&#8217;s an example of how to use <code>async/await</code>:</p>



<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_function():
  # Your asynchronous code here

# Run the async function using `await`
result = await my_function()
</pre>



<p>Now, let&#8217;s talk about <strong>async lambda functions in Python</strong>. Traditionally, lambda functions are used for writing short, simple, and anonymous functions. However, there is no direct support for async lambda functions in Python. </p>



<p>To achieve asynchronous behavior, you can leverage asynchronous generator expressions and the <code><a href="https://blog.finxter.com/python-__anext__-and-__aiter__-magic-methods/">__anext__</a></code> method, also described <a href="https://stackoverflow.com/questions/40746213/how-to-use-await-in-a-python-lambda">here</a>.</p>



<p>Remember that using async lambda might result in less readable and maintainable code, so use them wisely and opt for more conventional async functions when possible.</p>



<h2 class="wp-block-heading">Async Functions in Detail</h2>



<h3 class="wp-block-heading">Async Def</h3>



<p><code>Async def</code> is utilized to define asynchronous functions in Python. Using the <code>async</code> keyword before the <code>def</code> statement, you can create functions that work well with <code>async</code> and <code>await</code> keywords. An asynchronous function runs concurrently, allowing your code to proceed, while waiting for a coroutine to complete.</p>



<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_function():
    # Do something asynchronously
    await sleep(1)
    return "Async result"
</pre>



<p>Utilizing <code>async def</code> in your code fosters more efficient and organized execution, especially when parallelism is key.</p>



<h3 class="wp-block-heading">Async With</h3>



<p>The <code>async with</code> statement is used in asynchronous context managers. These managers provide an <code>__aenter__()</code> and <code>__aexit__()</code> coroutine method, and ensure that resources are acquired and released in an efficient manner. Within the <code>async with</code> block, resources can be used asynchronously, improving the overall execution of the code.</p>



<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 read_file():
    async with aiohttp.ClientSession() as session:
        async with session.get('https://example.com') as response:
            content = await response.text()
            return content
</pre>



<p>Using <code>async with</code>, you can manage resources efficiently in asynchronous environments.</p>



<h3 class="wp-block-heading">Lambda Functions</h3>



<p>Lambda functions are anonymous, single-expression functions in Python that are declared using the <code>lambda</code> keyword. These functions are concise and useful when you need small, throwaway functions for specific operations.</p>



<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="">square = lambda x: x**2
result = square(4)
print(result) # Output: 16
</pre>



<p>Lambda functions can be used as arguments for higher-order functions or as key functions in sorting operations.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f517.png" alt="🔗" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/daily-python-puzzle-sorting-lambda-function/">Python Lambda Sort Key</a></p>



<h3 class="wp-block-heading">Lambda Expression</h3>



<p>A lambda expression is used in a lambda function and typically consists of a single expression that operates on the provided input and returns the output. The expression does not include any return statement, as the output is directly returned from the expression.</p>



<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="">sum_lambda = lambda x, y: x + y
result = sum_lambda(2, 3)
print(result) # Output: 5
</pre>



<p></p>



<h2 class="wp-block-heading">Working with Asyncio</h2>



<h3 class="wp-block-heading">Importing Asyncio</h3>



<p>To begin working with <strong><code>asyncio</code></strong> in Python, you need to import the module into your script. Add the following line at the beginning of your code:</p>



<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
</pre>



<p>This will make the <code>asyncio</code> module available and allow you to use its methods and functions.</p>



<h3 class="wp-block-heading">Asyncio Tasks</h3>



<p>To work with asynchronous functions, start by declaring your functions with the <code>async</code> keyword. For example:</p>



<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_function():
    # Your asynchronous code
</pre>



<p>When you want to call an async function, use the <code>await</code> keyword:</p>



<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="">await my_function()
</pre>



<p>However, you must call async functions within the context of another async function. You can create and manage tasks using <code>asyncio.create_task()</code> and <code>asyncio.gather()</code> to run your functions concurrently:</p>



<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 main():
    task1 = asyncio.create_task(my_function())
    task2 = asyncio.create_task(another_function())

    await asyncio.gather(task1, task2)
</pre>



<h3 class="wp-block-heading">Asyncio Multithreading</h3>



<p class="has-global-color-8-background-color has-background">Multithreading in <code>asyncio</code> can be achieved using the <strong><code>asyncio</code></strong> runtime to run asynchronous functions concurrently. Although it&#8217;s not technically multithreading, since Python&#8217;s Global Interpreter Lock (GIL) prevents true parallel execution, the <strong><code>asyncio</code></strong> library allows you to write code in a parallel manner using coroutines.</p>



<p>To achieve &#8220;multithreading&#8221; using <code>asyncio</code>, create multiple tasks and run them concurrently using <code>asyncio.gather()</code>:</p>



<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_function1():
    # Your first async function

async def my_function2():
    # Your second async function

async def main():
    await asyncio.gather(my_function1(), my_function2())

# Call the main() function to execute the program
asyncio.run(main())
</pre>



<h3 class="wp-block-heading">Close Asyncio</h3>



<p>When you&#8217;re finished with your asynchronous tasks, it&#8217;s essential to close the asyncio event loop properly. To close the loop, use the <code>loop.close()</code> method:</p>



<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="">loop = asyncio.get_event_loop()
# Your asyncio code
loop.close()
</pre>



<p>By closing the event loop, you ensure that any resources are freed, and you prevent memory leaks.</p>



<p>Keep in mind the <code>loop.close()</code> method is only necessary for certain cases, like when you create custom event loops. If you use <code>asyncio.run()</code> to manage the event loop, the loop will be closed automatically.</p>



<p></p>



<h2 class="wp-block-heading">Frequently Asked Questions</h2>



<h3 class="wp-block-heading">How can I use asyncio with Python lambda functions?</h3>



<p>To use asyncio with Python lambda functions, you can define an async function in your code and then call <code>asyncio.get_event_loop().run_until_complete(your_async_function())</code> inside your regular synchronous lambda function.</p>



<h3 class="wp-block-heading">Can Python lambda functions be used as coroutines?</h3>



<p>No, Python lambda functions cannot be used as coroutines directly. Python lacks an async lambda syntax, so you cannot define an <code>async def</code> within a lambda function (<a href="https://stackoverflow.com/questions/40746213/how-to-use-await-in-a-python-lambda">source</a>). If you require coroutine functionality, you will need to use normal <code>async def</code> functions and not lambda functions.</p>



<h3 class="wp-block-heading">Is it possible to use async partial in Python lambda functions?</h3>



<p>Unfortunately, you cannot use <code>async partial</code> in Python lambda functions directly. The async partial functionality requires the use of async syntax, which is not supported in lambda functions. As a workaround, you can define an async function with the desired functionality outside of the lambda function and use it within your code.</p>



<h3 class="wp-block-heading">How do you return an async value from a Python lambda?</h3>



<p>Since Python does not support async lambda syntax, you cannot return an async value directly from a lambda function. Instead, you can create a separate async function and use the <code>await</code> keyword inside this function to return the desired async value. Call this async function inside your synchronous lambda function using the <code>asyncio.get_event_loop().run_until_complete()</code> method.</p>



<h3 class="wp-block-heading">How can I call an async method inside a lambda function?</h3>



<p>To call an async method inside a lambda function, you&#8217;ll need to define the async method outside of the lambda function and use the <code>asyncio.get_event_loop().run_until_complete()</code> method within the lambda function. This allows you to call and await the async method&#8217;s completion, integrating the asynchronous operation into your lambda function.</p>



<h3 class="wp-block-heading">Can one lambda function invoke another asynchronously in Python?</h3>



<p>Yes, one lambda function can invoke another asynchronously in Python. To do this, you can use the <code>invoke</code> method from the AWS SDK for Python (Boto3) with the <code>InvocationType</code> parameter set to <code>'Event'</code>. This will trigger an asynchronous invocation of the target lambda function, allowing the calling function to continue without waiting for the invoked function to complete (<a href="https://stackoverflow.com/questions/58202522/calling-an-aws-lambda-function-asynchronously-from-python-with-async-await">source</a>).</p>



<p>Also make sure to check out our related articles on the Asynchronous Python functionality! <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<p><strong>Recommended</strong>: </p>



<ul class="wp-block-list">
<li><a href="https://blog.finxter.com/python-async-await-mastering-concurrent-programming/">Python Async Await: Mastering Concurrent Programming</a></li>



<li><a href="https://blog.finxter.com/python-async-for-mastering-asynchronous-iteration-in-python/">Python Async For: Mastering Asynchronous Iteration in Python</a></li>



<li><a href="https://blog.finxter.com/python-async-function/">Python Async Function</a></li>



<li><a href="https://blog.finxter.com/python-async-generator-mastering-asyncio-in-modern-applications/">Python Async Generator: Mastering Asyncio in Modern Applications</a></li>



<li><a href="https://blog.finxter.com/python-async-with-statement-simplifying-asynchronous-code/">Python Async With Statement — Simplifying Asynchronous Code</a></li>
</ul>
<p>The post <a href="https://blog.finxter.com/python-async-lambda-exploring-its-applications-and-usage/">Python Async Lambda: Exploring its Applications and Usage</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python Async Generator: Mastering Asyncio in Modern Applications</title>
		<link>https://blog.finxter.com/python-async-generator-mastering-asyncio-in-modern-applications/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Wed, 20 Sep 2023 09:15:42 +0000</pubDate>
				<category><![CDATA[async]]></category>
		<category><![CDATA[Distributed Systems]]></category>
		<category><![CDATA[Parallel Programming]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1651678</guid>

					<description><![CDATA[<p>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 the complexity of threads. ... <a title="Python Async Generator: Mastering Asyncio in Modern Applications" class="read-more" href="https://blog.finxter.com/python-async-generator-mastering-asyncio-in-modern-applications/" aria-label="Read more about Python Async Generator: Mastering Asyncio in Modern Applications">Read more</a></p>
<p>The post <a 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 href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Asyncio Overview</h2>



<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>



<h2 class="wp-block-heading">Async and Await Key Concepts</h2>



<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>



<p>To work effectively with asyncio, there are two essential concepts you should understand: <code>async</code> and <code>await</code>.</p>



<ul class="wp-block-list">
<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>



<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>
</ul>



<p>Here&#8217;s a simple example incorporating these concepts:</p>



<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
my_task = asyncio.create_task(my_coroutine())

# Run the event loop until the task is completed
asyncio.run(my_task)
</pre>



<p></p>



<h2 class="wp-block-heading">Generators and Asyncio</h2>



<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>



<p>You can learn everything about generators in our Finxter tutorial here:</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="Understanding Generators In Python" width="937" height="527" src="https://www.youtube.com/embed/2Ls0b1gjz2A?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" 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>



<p><strong>Generators are particularly useful when working with asynchronous programming, like when using the <code>asyncio</code> library.</strong> </p>



<h3 class="wp-block-heading">Yield Expressions and Statements</h3>



<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>



<p>There are two types of <code>yield</code> expressions you should be familiar with: </p>



<ul class="wp-block-list">
<li>the <code>yield</code> expression and </li>



<li>the <code>yield from</code> statement.</li>
</ul>



<p>A simple <code>yield</code> expression in a generator function might look like this:</p>



<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
</pre>



<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>



<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)
</pre>



<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>



<p>Here&#8217;s an example of how you might use <code>yield from</code> in a generator:</p>



<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)
</pre>



<p>This code will output:</p>



<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
0
1
2
End
</pre>



<p></p>



<h2 class="wp-block-heading">Python Async Generators</h2>



<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>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" 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="auto, (max-width: 988px) 100vw, 988px" /></figure>
</div>


<p>Here is an example of creating an asynchronous generator:</p>



<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
</pre>



<h3 class="wp-block-heading">Using Async Generators</h3>



<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>



<p>Here&#8217;s an example of using <code>async for</code> to work with the async generator:</p>



<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
if __name__ == "__main__":
    asyncio.run(main())
</pre>



<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>



<h3 class="wp-block-heading">Errors in Async Generators</h3>



<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>



<p>Here&#8217;s an example that shows how to handle errors in async generators:</p>



<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
if __name__ == "__main__":
    asyncio.run(main())
</pre>


<div class="wp-block-image">
<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>
</div>


<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>



<h2 class="wp-block-heading">Advanced Topics</h2>


<div class="wp-block-image">
<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>
</div>


<h3 class="wp-block-heading">Multiprocessing and Threading</h3>



<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>



<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>



<p>Using <code>ThreadPoolExecutor</code> and <code>ProcessPoolExecutor</code>, you can manage multiple threads and processes, respectively. </p>



<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>



<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
from 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)
</pre>



<h3 class="wp-block-heading">Contextlib and Python Asyncio</h3>



<p><code>contextlib</code> is a useful Python library for context and resource management, and it readily integrates with <code>asyncio</code>. </p>



<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>



<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
from contextlib import asynccontextmanager

@asynccontextmanager
async 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)
</pre>



<h3 class="wp-block-heading">Asyncio and Database Operations</h3>



<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>



<p>Here&#8217;s an example using the <code>aiomysql</code> library for interacting with a MySQL database:</p>



<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
import 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()
</pre>



<h3 class="wp-block-heading">Performance and Optimization Tips</h3>



<p>To enhance the performance of your <code>asyncio</code> program, consider the following optimization tips:</p>



<ul class="wp-block-list">
<li>Profile your code to identify performance bottlenecks</li>



<li>Use <code>asyncio.gather(*coroutines)</code> to schedule multiple coroutines concurrently, which minimizes the total execution time</li>



<li>Manage the creation and destruction of tasks using <code>asyncio.create_task()</code> and <code>await task.cancel()</code></li>



<li>Limit concurrency when working with resources that might become overwhelmed by too many simultaneous connections</li>
</ul>



<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>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f9d1-200d-1f4bb.png" alt="🧑‍💻" 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>



<p></p>



<h2 class="wp-block-heading">Frequently Asked Questions</h2>



<figure class="wp-block-image 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_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>



<h3 class="wp-block-heading">How to create an async generator in Python?</h3>



<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>



<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
</pre>



<h3 class="wp-block-heading">What is the return type of an async generator?</h3>



<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>



<h3 class="wp-block-heading">How to use &#8216;send&#8217; with an async generator?</h3>



<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>



<h3 class="wp-block-heading">Why is an async generator not iterable?</h3>



<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>



<h3 class="wp-block-heading">How to work with an async iterator?</h3>



<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>



<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)
</pre>



<h3 class="wp-block-heading">Can I use &#8216;yield from&#8217; with an async generator?</h3>



<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>



<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
</pre>



<p></p>



<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>



<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>


<div class="wp-block-image">
<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 loading="lazy" decoding="async" width="993" height="823" src="https://blog.finxter.com/wp-content/uploads/2023/09/robotaxi-1.gif" alt="" class="wp-image-1651683"/></a></figure>
</div>


<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" 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 – Scale Your Fleet to $1M! A Python Mini Game Made By ChatGPT</a></p>
<p>The post <a 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 href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python Async Requests: Getting URLS Concurrently via HTTP(S)</title>
		<link>https://blog.finxter.com/python-async-requests-getting-urls-concurrently-via-https/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Sun, 17 Sep 2023 14:22:00 +0000</pubDate>
				<category><![CDATA[async]]></category>
		<category><![CDATA[Distributed Systems]]></category>
		<category><![CDATA[Parallel Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Requests]]></category>
		<category><![CDATA[Web Scraping]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1651606</guid>

					<description><![CDATA[<p>As a Python developer, you may often deal with making HTTP requests to interact with APIs or to retrieve information from web pages. By default, these requests can be slow and block your program&#8217;s execution, making your code less efficient. This is where Python&#8217;s async requests come to the rescue. Asynchronous HTTP requests allow your ... <a title="Python Async Requests: Getting URLS Concurrently via HTTP(S)" class="read-more" href="https://blog.finxter.com/python-async-requests-getting-urls-concurrently-via-https/" aria-label="Read more about Python Async Requests: Getting URLS Concurrently via HTTP(S)">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/python-async-requests-getting-urls-concurrently-via-https/">Python Async Requests: Getting URLS Concurrently via HTTP(S)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>As a <a href="https://blog.finxter.com/python-developer-income-and-opportunity/">Python developer</a>, you may often deal with <strong>making HTTP requests to interact with APIs or to retrieve information from web pages</strong>. By default, these requests can be slow and block your program&#8217;s execution, making your code less efficient. </p>



<p>This is where <strong>Python&#8217;s async requests</strong> come to the rescue. Asynchronous HTTP requests allow your program to continue executing other tasks while waiting for the slower request operations to complete, improving your code&#8217;s overall performance and response time significantly.</p>



<p>The core of this non-blocking approach in Python relies on the <code><a href="https://blog.finxter.com/how-to-check-asyncio-package-version-in-python/">asyncio</a></code> and <code><a href="https://blog.finxter.com/how-to-install-aiohttp-in-python/">aiohttp</a></code> libraries, which provide the necessary tools to perform efficiently and asynchronously. Using these libraries, you can build powerful async HTTP clients to handle multiple requests concurrently without stalling your program&#8217;s main thread.</p>



<p>Incorporating Python async requests into your projects can help you tackle complex web scraping scenarios, handling tasks like <a href="https://blog.finxter.com/fix-rate-limit-error-in-openai-codex/">rate limiting</a> and error recovery. </p>



<h2 class="wp-block-heading">First Things First: Understanding Asynchronous Requests</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="683" src="https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4709285-1024x683.webp" alt="" class="wp-image-1651623" srcset="https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4709285-1024x683.webp 1024w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4709285-300x200.webp 300w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4709285-768x512.webp 768w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4709285.webp 1125w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h3 class="wp-block-heading">Basic Principles of Asynchronous Requests</h3>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f40d.png" alt="🐍" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f40d.png" alt="🐍" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f40d.png" alt="🐍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Asynchronous requests</strong> play a crucial role in improving the efficiency of your code when dealing with network tasks. <br><br>When you send an asynchronous request, your program can continue executing other tasks without waiting for the request to complete. <br><br>This is possible because of the <code>async/await</code> syntax in Python, which allows you to write asynchronous code more easily. In essence, this keyword pair breaks down asynchronous code into smaller, manageable pieces to provide better readability and maintainability.</p>



<p>Here&#8217;s a brief explanation of <code>async</code> and <code>await</code>:</p>



<ul class="wp-block-list">
<li><code>async</code>: This keyword is used to <a href="https://blog.finxter.com/python-async-function/">define a function as asynchronous</a>, which means it&#8217;s able to run concurrently with other tasks in your code.</li>



<li><code>await</code>: This keyword is used within an <code>async</code> function to <a href="https://blog.finxter.com/python-async-await-mastering-concurrent-programming/">wait for the async function&#8217;s result</a>, allowing other tasks to proceed in the meantime.</li>
</ul>



<p>Here&#8217;s a simple example showcasing the <code>async/await</code> syntax:</p>



<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 example_async_function():
    print("Task is starting")
    await asyncio.sleep(1)
    print("Task is complete")

async def main():
    task = asyncio.create_task(example_async_function())
    await task

asyncio.run(main())
</pre>



<h3 class="wp-block-heading">Synchronous vs Asynchronous Requests</h3>



<p>When working with network requests, it&#8217;s important to understand the difference between synchronous and asynchronous requests.</p>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Synchronous requests</strong> involve waiting for the response of each request before proceeding, and it&#8217;s a typical way to handle requests in Python. However, this can lead to slower execution times, especially when dealing with numerous requests or slow network responses.</p>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Asynchronous requests</strong> allow you to send multiple requests at the same time, without waiting for their individual responses. This means your program can continue with other tasks while the requests are being processed, significantly improving performance in network-intensive scenarios.</p>



<p>Here&#8217;s a basic comparison between synchronous and asynchronous requests:</p>



<ul class="wp-block-list">
<li><strong>Synchronous Requests:</strong>
<ul class="wp-block-list">
<li>Send a request and wait for its response</li>



<li>Block the execution of other tasks while waiting</li>



<li>Can cause delays if there are many requests or slow network responses</li>
</ul>
</li>



<li><strong>Asynchronous Requests:</strong>
<ul class="wp-block-list">
<li>Send multiple requests concurrently</li>



<li>Don&#8217;t block the execution of other tasks while waiting for responses</li>



<li>Improve performance in network-heavy scenarios</li>
</ul>
</li>
</ul>



<p>For example, the popular <a href="https://blog.finxter.com/python-requests-library/"><code>requests</code> library</a> in Python handles synchronous requests, while libraries like <code>aiohttp</code> handle asynchronous requests. If you&#8217;re working with multiple network requests in your code, it&#8217;s highly recommended to implement async/await for optimal efficiency and performance.</p>



<h2 class="wp-block-heading">Python and Asyncio</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="683" src="https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-3771091-1024x683.jpeg" alt="" class="wp-image-1651624" srcset="https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-3771091-1024x683.jpeg 1024w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-3771091-300x200.jpeg 300w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-3771091-768x512.jpeg 768w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-3771091.jpeg 1125w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h3 class="wp-block-heading">Understanding Asyncio</h3>



<p>Asyncio is a library introduced in Python 3.4 and has evolved rapidly, especially till Python 3.7. It provides a foundation for writing asynchronous code using the <code>async</code>/<code>await</code> syntax. With asyncio, you can execute concurrent programming in Python, making your code more efficient and responsive. </p>



<p>The library is structured around <strong>coroutines</strong>, an approach that allows concurrent execution of multiple tasks within an <strong>event loop</strong>. A coroutine is a specialized version of a <a href="https://blog.finxter.com/python-return-generator-from-function/">Python generator function</a> that can suspend and resume its execution. By leveraging coroutines, you can execute multiple tasks concurrently without threading or multiprocessing.</p>



<p>Asyncio makes use of <strong>futures</strong> to represent the results of computations that may not have completed yet. Using asyncio&#8217;s <strong>coroutine function</strong>, you can create coroutines that perform asynchronous tasks, like making HTTP requests or handling I/O operations.</p>



<h3 class="wp-block-heading">Using Asyncio in Python</h3>



<p>To utilize <code>asyncio</code> in your Python projects, your code must incorporate the <strong><code>asyncio</code> library</strong>. The primary method of executing asynchronous tasks is by using an <strong>event loop</strong>. In <a href="https://blog.finxter.com/check-python-version-from-command-line-and-in-script/">Python 3.7 and later</a>, you can use <code>asyncio.run()</code> to create and manage the event loop for you. </p>



<p>With asyncio, you can declare a function as a coroutine by using the <code>async</code> keyword. To call a coroutine, use the <code>await</code> keyword, which allows the coroutine to yield control back to the event loop and continue with other tasks.</p>



<p>Here&#8217;s an example of using asyncio:</p>



<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 greet(name, delay):
    await asyncio.sleep(delay)
    print(f"Hello, {name}!")

async def main():
    task1 = asyncio.ensure_future(greet("Alice", 1))
    task2 = asyncio.ensure_future(greet("Bob", 2))

    await task1
    await task2

asyncio.run(main())
</pre>



<p>In the example above, we created two <strong>asyncio tasks</strong> and added them to the event loop using <code>asyncio.ensure_future()</code>. When <code>await</code> is encountered, the coroutine is suspended, and the event loop can switch to another task. This continues until all tasks in the event loop are complete.</p>



<p>Now let&#8217;s get to the meat. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f969.png" alt="🥩" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f447.png" alt="👇" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h2 class="wp-block-heading">Using the Requests Library for Synchronous HTTP Requests</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="683" src="https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-5935794-1024x683.webp" alt="" class="wp-image-1651625" srcset="https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-5935794-1024x683.webp 1024w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-5935794-300x200.webp 300w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-5935794-768x512.webp 768w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-5935794.webp 1125w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p class="has-global-color-8-background-color has-background">The <a href="https://docs.python-requests.org/en/latest/"><code>requests</code></a> library is a popular choice for making HTTP requests in Python. However, it&#8217;s primarily designed for synchronous operations, which means it may not be the best choice for handling asynchronous requests.</p>



<p>To make a simple synchronous GET request using the requests library, you would do the following:</p>



<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 requests

response = requests.get('https://api.example.com/data')
print(response.content)
</pre>



<p>While the requests library is powerful and easy to use, it doesn&#8217;t natively support asynchronous requests. This can be a limitation when you have to make multiple requests concurrently to improve performance and reduce waiting time.</p>



<h2 class="wp-block-heading">Asynchronous HTTP Requests with HTTPX</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="683" src="https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4709366-1024x683.webp" alt="" class="wp-image-1651626" srcset="https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4709366-1024x683.webp 1024w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4709366-300x200.webp 300w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4709366-768x512.webp 768w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4709366.webp 1125w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>HTTPX is a fully featured HTTP client for Python, providing both synchronous and asynchronous APIs. With support for HTTP/1.1 and HTTP/2, it is a modern alternative to the popular Python <code>requests</code> library.</p>



<h3 class="wp-block-heading">Why Use HTTPX?</h3>



<p>HTTPX offers improved efficiency, performance, and additional features compared to other HTTP clients. Its interface is similar to <code>requests</code>, making it easy to switch between the two libraries. Moreover, HTTPX supports asynchronous HTTP requests, allowing your application to perform better in scenarios with numerous concurrent tasks.</p>



<h3 class="wp-block-heading">HTTPX Asynchronous Requests</h3>



<p class="has-global-color-8-background-color has-background">To leverage the asynchronous features of HTTPX, you can use the <code>httpx.AsyncClient</code> class. This enables you to make non-blocking HTTP requests using Python&#8217;s <code>asyncio</code> library. Asynchronous requests can provide significant performance benefits and enable the use of long-lived network connections, such as WebSockets.</p>



<p>Here is an example to demonstrate how async requests can be made using <code>httpx.AsyncClient</code>:</p>



<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 httpx
import asyncio

async def fetch(url):
    async with httpx.AsyncClient() as client:
        response = await client.get(url)
        return response.text

async def main():
    urls = ['https://www.google.com', 'https://www.example.com']
    tasks = [fetch(url) for url in urls]
    contents = await asyncio.gather(*tasks)
    for content in contents:
        print(content[:1000])  # Print the first 1000 characters of each response

asyncio.run(main())
</pre>



<p>Here&#8217;s a breakdown of the code:</p>



<ol class="wp-block-list">
<li><code>fetch</code>: This asynchronous function fetches the content of a given URL.</li>



<li><code>main</code>: This asynchronous function initializes the tasks to fetch content from a list of URLs and then gathers the results.</li>



<li><code>asyncio.run(main())</code>: This runs the main asynchronous function.</li>
</ol>



<p>The code will fetch the content of the URLs in <code>urls</code> concurrently and print the first 1000 characters of each response. Adjust as needed for your use case!</p>



<p></p>



<h2 class="wp-block-heading">Managing Sessions and Connections</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="683" src="https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4709291-1024x683.webp" alt="" class="wp-image-1651627" srcset="https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4709291-1024x683.webp 1024w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4709291-300x200.webp 300w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4709291-768x512.webp 768w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4709291.webp 1125w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h3 class="wp-block-heading">Session Management in Async Requests</h3>



<p class="has-global-color-8-background-color has-background">When working with asynchronous requests in Python, you can use sessions to manage connections. The <code>aiohttp.ClientSession</code> class is designed to handle multiple requests and maintain connection <a href="https://blog.finxter.com/python-multiprocessing-pool-ultimate-guide/">pools</a>.</p>



<p>To get started, create an instance of the <code>aiohttp.ClientSession</code> class:</p>



<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 aiohttp

async with aiohttp.ClientSession() as session:
    # Your asynchronous requests go here
</pre>



<p>Using the <a href="https://blog.finxter.com/python-one-line-with-statement/"><code>with</code> statement</a> ensures that the session is properly closed when the block is exited. Within the <code><a href="https://blog.finxter.com/python-async-with-statement-simplifying-asynchronous-code/">async with</a></code> block, you can send multiple requests using the same session object. This is beneficial if you are interacting with the same server or service, as it can reuse connections and reduce overhead.</p>



<h3 class="wp-block-heading">Connection Management with TCPConnector</h3>



<p class="has-global-color-8-background-color has-background">Besides sessions, one way to manage connections is by using the <code>aiohttp.TCPConnector</code> class. The <code>TCPConnector</code> class helps in controlling the behavior of connections, such as limiting the number of simultaneous connections, setting connection timeouts, and configuring SSL settings.</p>



<p>Here is how you can create a custom <code>TCPConnector</code> and use it with your <code>ClientSession</code>:</p>



<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 aiohttp

connector = aiohttp.TCPConnector(limit=10, ssl=True)
async with aiohttp.ClientSession(connector=connector) as session:
    # Your asynchronous requests go here
</pre>



<p>In this example, the <code>TCPConnector</code> is set to limit the number of concurrent connections to 10 and enforce SSL connections to ensure secure communication.</p>



<h2 class="wp-block-heading">Implementing Concurrency and Threading</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="683" src="https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4705612-1024x683.jpeg" alt="" class="wp-image-1651628" srcset="https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4705612-1024x683.jpeg 1024w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4705612-300x200.jpeg 300w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4705612-768x512.jpeg 768w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4705612.jpeg 1125w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h3 class="wp-block-heading">Concurrency in Async Requests</h3>



<p>Concurrency for efficient and fast execution of your Python programs involves overlapping the execution of multiple tasks, which is especially useful for I/O-bound tasks, where waiting for external resources can slow down your program. </p>



<p>One way to achieve concurrency in Python is by using <code>asyncio</code>. This module, built specifically for asynchronous I/O operations, allows you to use <code>async</code> and <code>await</code> keywords to manage concurrent execution of tasks without the need for threads or processes.</p>



<p>For example, to make multiple HTTP requests concurrently, you can use an asynchronous library like <code>aiohttp</code>. Combined with <code>asyncio</code>, your code might look like this:</p>



<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 aiohttp
import asyncio

async def fetch(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

async def main():
    urls = ['https://example.com', 'https://another.example.com']
    tasks = [fetch(url) for url in urls]
    responses = await asyncio.gather(*tasks)

asyncio.run(main())
</pre>



<h3 class="wp-block-heading">Threading in Async Requests</h3>



<p>Another way to implement concurrency in Python is by using threads. Threading is a technique that allows your code to run concurrently by splitting it into multiple lightweight threads of execution. The <code>threading</code> module provides features to create and manage threads easily.</p>



<p>For instance, if you want to use threads to make multiple HTTP requests simultaneously, you can employ the <code>ThreadPoolExecutor</code> from the <code>concurrent.futures</code> module combined with the <code>requests</code> library:</p>



<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 requests
from concurrent.futures import ThreadPoolExecutor

def fetch(url):
    response = requests.get(url)
    return response.text

def main():
    urls = ['https://example.com', 'https://another.example.com']
    with ThreadPoolExecutor(max_workers=len(urls)) as executor:
        responses = list(executor.map(fetch, urls))

main()
</pre>



<p>In this example, the <code>ThreadPoolExecutor</code> creates a pool of worker threads that execute the <code>fetch</code> function concurrently. The number of threads is determined by the length of the <code>urls</code> list, ensuring that all requests are handled in parallel.</p>



<p></p>



<h2 class="wp-block-heading">Working with URLs in Async Requests</h2>



<p class="has-global-color-8-background-color has-background">When managing and manipulating URLs in async requests, you might need to handle various tasks such as encoding parameters, handling redirects, and constructing URLs properly. Thankfully, Python provides the <code>urllib.parse</code> module for handling URL manipulations.</p>



<p>For instance, you may want to add query parameters to a URL. To do this, you can use the <code>urllib.parse.urlencode</code> function:</p>



<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="">from urllib.parse import urlencode, urljoin

base_url = "https://api.example.com/data?"
params = {"key1": "value1", "key2": "value2"}

url = urljoin(base_url, urlencode(params))
</pre>



<p>After constructing the URL with query parameters, you can pass it to your async request function:</p>



<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 main():
    url = urljoin(base_url, urlencode(params))
    data = await fetch_data(url)
    print(data)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
</pre>



<p>By properly handling URLs and leveraging async requests, you can efficiently fetch data in Python while maintaining a clear and organized code structure.</p>



<h2 class="wp-block-heading">Handling Errors and Timeouts</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="683" src="https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4709374-1024x683.webp" alt="" class="wp-image-1651629" srcset="https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4709374-1024x683.webp 1024w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4709374-300x200.webp 300w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4709374-768x512.webp 768w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4709374.webp 1125w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h3 class="wp-block-heading">Error Handling in Async Requests</h3>



<p class="has-global-color-8-background-color has-background">When working with asynchronous requests in Python, it&#8217;s important to properly handle errors and exceptions that might occur. To do this, you can use the <code>try</code> and <code>except</code> statements. When a request fails or encounters an error, the exception will be caught in the <code>except</code> block, allowing you to handle the error gracefully.</p>



<p>For example, when using the <code>asyncio</code> and <code>aiohttp</code> libraries, you might structure your request and error handling like this:</p>



<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
import aiohttp

async def fetch_url(url):
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as response:
                data = await response.text()
                return data
    except Exception as e:
        print(f"An error occurred while fetching {url}: {str(e)}")
        return None

results = await asyncio.gather(*[fetch_url(url) for url in urls])
</pre>



<p>In this example, if an exception is encountered during the request, the error message will be printed and the function will return <code>None</code>, allowing your program to continue processing other URLs.</p>



<h3 class="wp-block-heading">Managing Timeouts in Async Requests</h3>



<p>Managing timeouts in async requests is crucial to ensure requests don&#8217;t run indefinitely, consuming resources and blocking progress in your program. Setting timeouts can help prevent long waits for unresponsive servers or slow connections.</p>



<p>To set a timeout for your async requests, you can use the <code>asyncio.wait_for()</code> function. This function takes a coroutine object and a timeout value as its arguments and will raise <code>asyncio.TimeoutError</code> if the timeout is reached.</p>



<p>Here&#8217;s an example using the <code>asyncio</code> and <code>aiohttp</code> libraries:</p>



<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
import aiohttp

async def fetch_url(url, timeout):
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as response:
                data = await asyncio.wait_for(response.text(), timeout=timeout)
                return data
    except asyncio.TimeoutError:
        print(f"Timeout reached while fetching {url}")
        return None
    except Exception as e:
        print(f"An error occurred while fetching {url}: {str(e)}")
        return None

results = await asyncio.gather(*[fetch_url(url, 5) for url in urls])
</pre>



<p>In this example, the requests will time out after 5 seconds, and the function will print a message indicating a timeout, then return <code>None</code>. This way, your program can continue processing other URLs after encountering a timeout without getting stuck in an endless wait.</p>



<h2 class="wp-block-heading">Frequently Asked Questions</h2>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="683" src="https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4855375-1024x683.webp" alt="" class="wp-image-1651630" srcset="https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4855375-1024x683.webp 1024w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4855375-300x200.webp 300w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4855375-768x512.webp 768w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-4855375.webp 1125w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h3 class="wp-block-heading">How do I send async HTTP requests in Python?</h3>



<p>To send asynchronous HTTP requests in Python, you can use a library like <a href="https://www.twilio.com/blog/asynchronous-http-requests-in-python-with-aiohttp">aiohttp</a>. This library allows you to make HTTP requests using the <code>async</code> and <code>await</code> keywords, which are built into Python 3.7 and later versions. To start, you&#8217;ll need to install aiohttp and then use it to write asynchronous functions for sending HTTP requests.</p>



<h3 class="wp-block-heading">Which library should I use for asyncio in Python requests?</h3>



<p>While the popular <a href="http://docs.python-requests.org/en/master/community/faq/">Requests library</a> doesn&#8217;t support asyncio natively, you can use alternatives like <a href="https://www.twilio.com/blog/asynchronous-http-requests-in-python-with-aiohttp">aiohttp</a> or <a href="https://www.python-httpx.org/">httpx</a> that were designed specifically for asynchronous programming. Both aiohttp and httpx allow you to utilize Python&#8217;s asyncio capabilities while providing a simple and familiar API similar to Requests.</p>



<h3 class="wp-block-heading">What are the differences between aiohttp and requests?</h3>



<p>The main differences between aiohttp and Requests lie in their approach to concurrency. aiohttp was built to work with Python&#8217;s asyncio library and uses asynchronous programming to allow for concurrent requests. On the other hand, Requests is a regular, synchronous HTTP library, which means it doesn&#8217;t inherently support concurrent requests or asynchronous programming.</p>



<h3 class="wp-block-heading">How can I call multiple APIs asynchronously in Python?</h3>



<p>By using an async-enabled HTTP library like <a href="https://www.twilio.com/blog/asynchronous-http-requests-in-python-with-aiohttp">aiohttp</a>, you can call multiple APIs asynchronously in your Python code. First, define separate async functions for the API calls you want to make, and then use the <code>asyncio.gather()</code> function to combine and execute these functions concurrently. This allows you to perform several API calls at once, reducing the overall time to process the requests.</p>



<h3 class="wp-block-heading">What is the use of async with statement in Python?</h3>



<p>The <code>async with</code> statement in Python is an asynchronous version of the regular <code>with</code> statement, which is used for managing resources such as file I/O or network connections. In an async context, the <code>async with</code> statement allows you to enter a context manager that expects an asynchronous exit, clean up resources upon exit, and use the <code>await</code> keyword to work with asynchronous operations.</p>



<h3 class="wp-block-heading">When should I use asynchronous programming in Python?</h3>



<p>Asynchronous programming in Python is beneficial when you&#8217;re working with I/O-bound tasks, such as network requests, web scraping, or file operations. By using async techniques, you can execute these tasks concurrently, thus reducing the overall execution time and improving performance. However, for CPU-bound tasks, using Python&#8217;s built-in <code>multiprocessing</code> module or regular multi-threading might be more suitable.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f40d.png" alt="🐍" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/python-async-function/">Python Async Function</a></p>
<p>The post <a href="https://blog.finxter.com/python-async-requests-getting-urls-concurrently-via-https/">Python Async Requests: Getting URLS Concurrently via HTTP(S)</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python Async For: Mastering Asynchronous Iteration in Python</title>
		<link>https://blog.finxter.com/python-async-for-mastering-asynchronous-iteration-in-python/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Fri, 15 Sep 2023 19:16:14 +0000</pubDate>
				<category><![CDATA[async]]></category>
		<category><![CDATA[Distributed Systems]]></category>
		<category><![CDATA[Parallel Programming]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1651578</guid>

					<description><![CDATA[<p>In Python, the async for construct allows you to iterate over asynchronous iterators, which yield values from asynchronous operations. You&#8217;ll use it when working with asynchronous libraries or frameworks where data fetching or processing happens asynchronously, such as reading from databases or making HTTP requests. The async for loop ensures that while waiting for data, ... <a title="Python Async For: Mastering Asynchronous Iteration in Python" class="read-more" href="https://blog.finxter.com/python-async-for-mastering-asynchronous-iteration-in-python/" aria-label="Read more about Python Async For: Mastering Asynchronous Iteration in Python">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/python-async-for-mastering-asynchronous-iteration-in-python/">Python Async For: Mastering Asynchronous Iteration in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="has-global-color-8-background-color has-background">In Python, the <code>async for</code> construct allows you to iterate over asynchronous iterators, which yield values from asynchronous operations. You&#8217;ll use it when working with asynchronous libraries or frameworks where data fetching or processing happens asynchronously, such as reading from databases or making HTTP requests. The <code>async for</code> loop ensures that while waiting for data, other tasks can run concurrently, improving efficiency in I/O-bound tasks.</p>



<p>Here&#8217;s a minimal example:</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="567" height="595" src="https://blog.finxter.com/wp-content/uploads/2023/09/async_222-1.gif" alt="" class="wp-image-1651586"/></figure>



<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_gen():
    for i in range(3):
        await asyncio.sleep(1)  # Simulate asynchronous I/O operation
        yield i

async def main():
    async for val in async_gen():
        print(val)

# To run the code: asyncio.run(main())
</pre>



<p>In this example, <code>async_gen</code> is an asynchronous generator that yields numbers from 0 to 2. Each number is yielded after waiting for 1 second (simulating an asynchronous operation). The <code>main</code> function demonstrates how to use the <code>async for</code> loop to iterate over the asynchronous generator.</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Understanding Python Async Keyword</h2>



<p>As a <a href="https://blog.finxter.com/python-developer-income-and-opportunity/">Python developer</a>, you might have heard of <strong>asynchronous programming</strong> and how it can help improve the efficiency of your code. </p>



<p>One powerful tool for working with asynchronous code is the <code>async for</code> loop, which allows you to iterate through asynchronous iterators while maintaining a non-blocking execution flow. By harnessing the power of <code>async for</code>, you will be able to write high-performing applications that can handle multiple tasks concurrently without being slowed down by blocking operations.</p>



<p>The <code>async for</code> loop is based on the concept of <strong><a href="https://blog.finxter.com/python-multiprocessing-pool-ultimate-guide/">asynchronous iterators</a></strong>, providing a mechanism to traverse through a series of awaitables while retrieving their results without blocking the rest of your program. This distinct feature sets it apart from traditional synchronous loops, and it plays an essential role in making your code concurrent and responsive, handling tasks such as network requests and other I/O-bound operations more efficiently.</p>



<p>To get started with <code>async for</code> in Python, you&#8217;ll need to use the <code>async def</code> keyword when creating <a href="https://blog.finxter.com/python-async-function/">asynchronous functions</a>, and make use of asynchronous context managers and generators. </p>



<p>When you deal with asynchronous programming in Python, the <code>async</code> keyword plays a crucial role. <strong><em>Asynchronous programming allows your code to handle multiple tasks simultaneously without blocking other tasks. </em></strong>This is particularly useful in scenarios where tasks need to be executed concurrently without waiting for each other to finish.</p>



<p>The <code>async</code> keyword in Python signifies that a function is a coroutine. Coroutines are a way of writing asynchronous code that looks similar to synchronous code, making it easier to understand. With coroutines, you can suspend and resume the execution of a function at specific points, allowing other tasks to run concurrently.</p>



<p>In Python, the <code>async</code> keyword is used in conjunction with the <code><a href="https://blog.finxter.com/python-async-await-mastering-concurrent-programming/">await</a></code> keyword. While <code>async</code> defines a coroutine function, <code>await</code> is used to call a coroutine and wait for it to complete. When you use the <code>await</code> keyword, the execution of the current coroutine is suspended, and other tasks are allowed to run. Once the <code>await</code> expression completes, the coroutine resumes its execution from where it left off.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/python-async-await-mastering-concurrent-programming/">Python Async Await: Mastering Concurrent Programming</a></p>



<p>Here&#8217;s an example of how you might use the <code>async</code> and <code>await</code> keywords in your Python code:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="1024" height="520" src="https://blog.finxter.com/wp-content/uploads/2023/09/image-81.png" alt="" class="wp-image-1651579" srcset="https://blog.finxter.com/wp-content/uploads/2023/09/image-81.png 1024w, https://blog.finxter.com/wp-content/uploads/2023/09/image-81-300x152.png 300w, https://blog.finxter.com/wp-content/uploads/2023/09/image-81-768x390.png 768w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<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 aiohttp
import asyncio

async def fetch_url(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

async def main():
    url = "https://www.example.com/"
    content = await fetch_url(url)
    print(content)

asyncio.run(main())
</pre>



<p>In this example, <code>fetch_url</code> is a coroutine defined using the <code>async</code> keyword. It makes a request to a specified URL and retrieves the content. The request and response handling is done asynchronously, allowing other tasks to run while waiting for the response. The <code>main</code> coroutine uses <code>await</code> to call <code>fetch_url</code> and waits for it to complete before printing the content.</p>



<h2 class="wp-block-heading">Async Function and Coroutine Objects</h2>



<p>In Python, asynchronous programming relies on <strong>coroutine objects</strong> to execute code concurrently without blocking the execution flow of your program. You can create coroutine objects by defining asynchronous functions using the <code>async def</code> keyword. Within these async functions, you can use the <code>await</code> keyword to call other asynchronous functions, referred to as <strong>async/await</strong> syntax.</p>



<p>To begin, define your asynchronous function using the <code>async</code> keyword, followed by <code>def</code>:</p>



<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_function():
    # your code here
</pre>



<p>While working with <strong>asynchronous functions</strong>, you&#8217;ll often encounter situations where you need to call other async functions. To do this, use the <code>await</code> keyword before the function call. This allows your program to wait for the result of the awaited function before moving on to the next line of code:</p>



<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_function():
    # your code here

async def my_async_function():
    result = await another_async_function()
</pre>



<p>Coroutine objects are created when you call an async function, but the function doesn&#8217;t execute immediately. Instead, these coroutines can be scheduled to run concurrently using an event loop provided by the <code>asyncio</code> library. Here&#8217;s an example of running a coroutine using <code>asyncio.run()</code>:</p>



<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_async_function():
    print("Hello, async!")

asyncio.run(my_async_function())
</pre>



<p>Remember that async functions are not meant to be called directly like regular functions. Instead, they should be awaited within another async function or scheduled using an event loop.</p>



<p>By using coroutine objects and the async/await syntax, you can write more efficient, readable, and performant code that manages concurrency and handles I/O bound tasks effectively. Keep in mind that async functions should primarily be used for I/O-bound tasks and not for CPU-bound tasks. For CPU-bound tasks, consider using multi-threading or multi-processing instead.</p>



<h2 class="wp-block-heading">The Fundamentals of AsyncIO</h2>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>AsyncIO</strong> is a Python library that provides support for writing asynchronous code utilizing the <code>async</code> and <code>await</code> syntax. It allows you to write concurrent code in a single-threaded environment, which can be more efficient and easier to work with than using multiple threads.</p>



<p>To start using AsyncIO, you need to import asyncio in your Python script. Once imported, the core component of AsyncIO is the <strong><a href="https://blog.finxter.com/python-async-await-mastering-concurrent-programming/">event loop</a></strong>. The event loop manages and schedules the execution of coroutines, which are special functions designed to work with asynchronous code. They are defined using the <code>async def</code> syntax.</p>



<p>Creating a coroutine is simple. For instance, here’s a basic example:</p>



<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("Hello AsyncIO!")

asyncio.run(my_coroutine())
</pre>



<p>In this example, <code>my_coroutine</code> is a coroutine that just prints a message. The <code>asyncio.run()</code> function is used to start and run the event loop, which in turn executes the coroutine.</p>



<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Coroutines</strong> play a crucial role in writing asynchronous code with AsyncIO. Instead of using callbacks or threads, coroutines use the <code>await</code> keyword to temporarily suspend their execution, allowing other tasks to run concurrently. This cooperative multitasking approach lets you write efficient, non-blocking code.</p>



<p>Here is an example showcasing the use of <code>await</code>:</p>



<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 say_after(delay, message):
    await asyncio.sleep(delay)
    print(message)

async def main():
    await say_after(1, "Hello")
    await say_after(2, "AsyncIO!")

asyncio.run(main()) 
</pre>



<p>In this example, the <code>say_after</code> coroutine takes two parameters: <code>delay</code> and <code>message</code>. The <code>await asyncio.sleep(delay)</code> line is used to pause the execution of the coroutine for the specified number of seconds. After the pause, the <code>message</code> is printed. The <code>main</code> coroutine is responsible for running two instances of <code>say_after</code>, and the whole script is run via <code>asyncio.run(main())</code>.</p>



<h2 class="wp-block-heading">Asynchronous For Loop</h2>



<p class="has-global-color-8-background-color has-background">In Python, you can use the <code>async for</code> statement to iterate asynchronously over items in a collection. It allows you to perform non-blocking iteration, making your code more efficient when handling tasks such as fetching data from APIs or handling user inputs in a graphical user interface.</p>



<p>In order to create an asynchronous iterator, you need to define an object with an <code><a href="https://blog.finxter.com/python-__anext__-and-__aiter__-magic-methods/">__aiter__()</a></code> method that returns itself, and an <code><a href="https://blog.finxter.com/python-__anext__-and-__aiter__-magic-methods/">__anext__()</a></code> method which is responsible for providing the next item in the collection. </p>



<p>For example:</p>



<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="">class AsyncRange:
    def __init__(self, start, end):
        self.start = start
        self.end = end

    def __aiter__(self):
        return self

    async def __anext__(self):
        if self.start >= self.end:
            raise StopAsyncIteration
        current = self.start
        self.start += 1
        return current
</pre>



<p>Once you have your asynchronous iterator, you can use the <code>async for</code> loop to iterate over the items in a non-blocking manner. Here is an example showcasing the usage of the <code>AsyncRange</code> iterator:</p>



<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 number in AsyncRange(0, 5):
        print(number)
        await asyncio.sleep(1)

asyncio.run(main())
</pre>



<p>In this example, the <code>AsyncRange</code> iterator is used in an <code>async for</code> loop, where each iteration in the loop pauses for one second using the <code>await asyncio.sleep(1)</code> line. Despite the delay, the loop doesn&#8217;t block the execution of other tasks because it is asynchronous.</p>



<p>It&#8217;s important to remember that the <code>async for</code>, <code>__aiter__()</code>, and <code>__anext__()</code> constructs should be used only in asynchronous contexts, such as in coroutines or with async context managers.</p>



<p>By utilizing the asynchronous for loop, you can write more efficient Python code that takes full advantage of the asynchronous programming paradigm. This comes in handy when dealing with multiple tasks that need to be executed concurrently and in non-blocking ways.</p>



<h2 class="wp-block-heading">Using Async with Statement</h2>



<p class="has-global-color-8-background-color has-background">When working with asynchronous programming in Python, you might come across the <code><a href="https://blog.finxter.com/python-async-with-statement-simplifying-asynchronous-code/">async with</a></code> statement. This statement is specifically designed for creating and utilizing asynchronous context managers. Asynchronous context managers are able to suspend execution in their <code><a href="https://blog.finxter.com/python-__enter__-magic-method/">__enter__</a></code> and <code><a href="https://blog.finxter.com/python-__exit__-magic-method/">__exit__</a></code> methods, providing an effective way to manage resources in a concurrent environment.</p>



<p>To use the <code>async with</code> statement, first, you need to define an asynchronous context manager. This can be done by implementing an <code>__aenter__</code> and an <code>__aexit__</code> method in your class, which are the asynchronous counterparts of the synchronous <code>__enter__</code> and <code>__exit__</code> methods used in regular context managers. </p>



<p>The <code><a href="https://blog.finxter.com/python-__aenter__-magic-method/">__aenter__</a></code> method is responsible for entering the asynchronous context, while the <code><a href="https://blog.finxter.com/python-__aexit__-magic-method/">__aexit__</a></code> method takes care of exiting the context and performing cleanup operations.</p>



<p>Here&#8217;s a simple example to illustrate the usage of the <code>async with</code> statement:</p>



<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 aiohttp
import asyncio

async def fetch_data(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

async def main():
    url = "https://example.com"
    data = await fetch_data(url)
    print(data)

asyncio.run(main())
</pre>



<p>In this example, we&#8217;re using the <code>aiohttp</code> library to fetch the contents of a webpage. By using <code>async with</code> when creating the <code>ClientSession</code> and the <code>session.get</code> contexts, we ensure that resources are effectively managed throughout their lifetime in an asynchronous environment.</p>



<h2 class="wp-block-heading">Time and Delays in Async</h2>



<p>The <code>time</code> and <code>asyncio.sleep</code> functions are essential components of managing time delays.</p>



<p>In asynchronous programming, using <code>time.sleep</code> is not recommended since it can block the entire execution of your script, causing it to become unresponsive. Instead, you should use <code>asyncio.sleep</code>, which is a non-blocking alternative specifically designed for asynchronous tasks.</p>



<p>To implement a time delay in your async function, simply use the <code>await asyncio.sleep(seconds)</code> syntax, replacing <code>seconds</code> with the desired number of seconds for the delay. For example:</p>


<div class="wp-block-image">
<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_2.gif" alt="" class="wp-image-1651581"/></figure>
</div>


<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 delay_task():
    print("Task started")
    await asyncio.sleep(2)
    print("Task completed after 2 seconds")

asyncio.run(delay_task())
</pre>



<p>This will cause a 2-second wait between printing &#8220;Task started&#8221; and &#8220;Task completed after 2 seconds&#8221; without blocking the overall execution of your script.</p>



<p>Timeouts can also play a significant role in async programming, preventing tasks from taking up too much time or becoming stuck in an infinite loop. </p>



<p>To set a timeout for an async task, you can use the <code>asyncio.wait_for</code> function:</p>


<div class="wp-block-image">
<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_22.gif" alt="" class="wp-image-1651582"/></figure>
</div>


<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 long_running_task():
    await asyncio.sleep(10)
    return "Task completed after 10 seconds"

async def main():
    try:
        result = await asyncio.wait_for(long_running_task(), timeout=5)
        print(result)
    except asyncio.TimeoutError:
        print("Task took too long to complete")

asyncio.run(main())
</pre>



<p>In this example, the <code>long_running_task</code> takes 10 seconds to complete, but we set a timeout of 5 seconds using <code>asyncio.wait_for</code>. When the task exceeds the 5-second limit, an <code>asyncio.TimeoutError</code> is raised, and the message &#8220;Task took too long to complete&#8221; is printed.</p>



<p>By understanding and utilizing <code>asyncio.sleep</code> and timeouts in your asynchronous programming, you can create efficient and responsive applications in Python.</p>



<h2 class="wp-block-heading">Concurrency with AsyncIO</h2>



<p>AsyncIO is a powerful library in Python that enables you to write concurrent code. By using the async/await syntax, you can create and manage coroutines, which are lightweight functions that can run concurrently in a single thread or event loop. This approach maximizes efficiency and responsiveness in your applications, especially when dealing with I/O-bound operations.</p>



<p>To start, you&#8217;ll need to define your coroutines using the <code>async def</code> keyword. This allows you to use the <code>await</code> keyword within the coroutine to yield control back to the event loop, thus enabling other coroutines to run. You can think of coroutines as tasks that run concurrently within the same event loop.</p>



<p>To manage the execution of coroutines, you&#8217;ll use the <code>asyncio.create_task()</code> function. This creates a task object linked to the coroutine which is scheduled and run concurrently with other tasks within the event loop. For example:</p>



<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("Hello, World!")

task = asyncio.create_task(my_coroutine())
</pre>



<p>To run multiple tasks concurrently, you can use the <code>asyncio.gather()</code> function. This function takes several tasks as arguments and starts them all concurrently. When all tasks are completed, it returns a list of their results:</p>



<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 task_one():
    await asyncio.sleep(1)
    return "Task one completed"

async def task_two():
    await asyncio.sleep(2)
    return "Task two completed"

async def main():
    results = await asyncio.gather(task_one(), task_two())
    print(results)

asyncio.run(main())
</pre>



<p>Another useful function is <code>asyncio.as_completed()</code>. This function returns an asynchronous iterator that yields coroutines in the order they complete. It can be helpful when you want to process the results of coroutines as soon as they are finished, without waiting for all of them to complete:</p>


<div class="wp-block-image">
<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_222.gif" alt="" class="wp-image-1651583"/></figure>
</div>


<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_task(duration):
    await asyncio.sleep(duration)
    return f"Task completed in {duration} seconds"

async def main():
    tasks = [my_task(1), my_task(3), my_task(2)]
    for coroutine in asyncio.as_completed(tasks):
        result = await coroutine
        print(result)

asyncio.run(main())
</pre>



<p>When working with AsyncIO, remember that your coroutines should always be defined using the <code>async</code> keyword, and any function that calls an asynchronous function should also be asynchronous. </p>



<p></p>



<h2 class="wp-block-heading">Generators, Futures and Transports</h2>



<p>In your journey with Python&#8217;s async programming, you will come across key concepts like generators, futures, and transports. Understanding these concepts will help you grasp the core principles of asynchronous programming in Python.</p>



<p class="has-global-color-8-background-color has-background"><strong><a href="https://blog.finxter.com/understanding-generators-in-python/">Generators</a></strong> are functions that use the <code>yield</code> keyword to produce a sequence of values without computing them all at once. Instead of returning a single value or a list, a generator can be paused at any point in its execution, only to be resumed later. This is especially useful in async programming as it helps manage resources efficiently.</p>



<p><code>yield from</code> is a construct that allows you to delegate part of a generator&#8217;s operations to another generator, ultimately simplifying the code. When using <code>yield from</code>, you include a subgenerator expression, which enables the parent generator to yield values from the subgenerator.</p>



<p>Futures represent the result of a computation that may not have completed yet. In the context of async programming, a <a href="https://docs.python.org/3/library/asyncio-future.html">future object</a> essentially acts as a placeholder for the eventual outcome of an asynchronous operation. Their main purpose is to enable the interoperation of low-level callback-based code with high-level async/await code. As a best practice, avoid exposing future objects in user-facing APIs.</p>



<p>Transports are low-level constructs responsible for handling the actual I/O operations. They implement the communication protocol details, allowing you to focus on the high-level async/await code. <a href="https://docs.python.org/3/library/asyncio-protocol.html#transports">Asyncio transports</a> provide a streamlined way to manage sockets, buffers, and other low-level I/O related tasks.</p>



<h2 class="wp-block-heading">Frequently Asked Questions</h2>



<h3 class="wp-block-heading">What are the main differences between &#8216;async for&#8217; and regular &#8216;for&#8217; loops?</h3>



<p>The main difference between <code>async for</code> and regular <code>for</code> loops in Python is that <code>async for</code> allows you to work with asynchronous iterators. This means that you can perform non-blocking I/O operations while iterating, helping to improve your program&#8217;s performance and efficiency. Regular <code>for</code> loops are used with synchronous code, where each iteration must complete before the next one begins.</p>



<h3 class="wp-block-heading">How can async for loop be implemented with list comprehensions?</h3>



<p>Unfortunately, <code>async for</code> cannot be directly used with list comprehensions since the syntax does not support asynchronous execution. Instead, when working with asynchronous code, you can use <code>asyncio.gather()</code> alongside a list comprehension to achieve a similar result. This approach allows you to run multiple asynchronous tasks concurrently and collect their results.</p>



<p>For example:</p>



<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 square(x):
    await asyncio.sleep(1)
    return x * x

async def main():
    numbers = [1, 2, 3, 4, 5]
    results = await asyncio.gather(*(square(num) for num in numbers))
    print(results)

asyncio.run(main())
</pre>



<h3 class="wp-block-heading">What are common patterns to efficiently use async in Python?</h3>



<p>To efficiently use <code>async</code> in Python, you can employ the following patterns:</p>



<ol class="wp-block-list">
<li>Use <code>asyncio</code> library features, such as <code>asyncio.gather()</code>, <code>asyncio.sleep()</code>, and event loops.</li>



<li>Write asynchronous functions with the <code>async def</code> syntax and use <code>await</code> to call other asynchronous functions.</li>



<li>Use context managers, such as <code>async with</code>, to handle resources that support asynchronous operations.</li>



<li>Use <code>async for</code> loops when working with asynchronous iterators to keep your code non-blocking.</li>
</ol>



<h3 class="wp-block-heading">How can you create an async range in Python?</h3>



<p>To create an async range in Python, you can implement an asynchronous iterator with a custom class that adheres to the async iterator protocol. The custom class should define an <code>__aiter__()</code> method to return itself and implement an <code>__anext__()</code> method that raises <code>StopAsyncIteration</code> when the range is exhausted. Here is an example:</p>



<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

class AsyncRange:
    def __init__(self, start, end):
        self.start = start
        self.end = end

    def __aiter__(self):
        return self

    async def __anext__(self):
        if self.start >= self.end:
            raise StopAsyncIteration
        current = self.start
        self.start += 1
        await asyncio.sleep(1)
        return current

</pre>



<h3 class="wp-block-heading">Are there any examples of creating an async iterator?</h3>



<p>Here&#8217;s an example of creating an async iterator using a custom class:</p>



<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

class AsyncCountdown:
    def __init__(self, count):
        self.count = count

    def __aiter__(self):
        return self

    async def __anext__(self):
        if self.count &amp;#x3C;= 0:
            raise StopAsyncIteration
        value = self.count
        self.count -= 1
        await asyncio.sleep(1)
        return value

async def main():
    async for value in AsyncCountdown(5):
        print(value)

asyncio.run(main())
</pre>



<h3 class="wp-block-heading">What is the correct way to use &#8216;async while&#8217; in Python?</h3>



<p>To use <code>async while</code> in Python, simply place the <code>await</code> keyword before an asynchronous function or expression within the body of the <code>while</code> loop. By doing so, the loop will execute the asynchronous code non-blocking, allowing other tasks to run concurrently. Here&#8217;s an example:</p>



<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_while_example():
    count = 5
    while count > 0:
        await asyncio.sleep(1)
        print(count)
        count -= 1

asyncio.run(async_while_example())
</pre>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/python-async-function/">Python Async Function</a></p>
<p>The post <a href="https://blog.finxter.com/python-async-for-mastering-asynchronous-iteration-in-python/">Python Async For: Mastering Asynchronous Iteration in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Python Async Await: Mastering Concurrent Programming</title>
		<link>https://blog.finxter.com/python-async-await-mastering-concurrent-programming/</link>
		
		<dc:creator><![CDATA[Emily Rosemary Collins]]></dc:creator>
		<pubDate>Wed, 13 Sep 2023 09:24:03 +0000</pubDate>
				<category><![CDATA[async]]></category>
		<category><![CDATA[Distributed Systems]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python Keywords]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=1651514</guid>

					<description><![CDATA[<p>Python&#8217;s async and await are powerful features that enable you to write asynchronous code to improve the performance of your applications, particularly when dealing with I/O-bound and high-level structured network code. Async and await are used with coroutines, which are special functions that can pause and resume their execution at specific points. This allows multiple ... <a title="Python Async Await: Mastering Concurrent Programming" class="read-more" href="https://blog.finxter.com/python-async-await-mastering-concurrent-programming/" aria-label="Read more about Python Async Await: Mastering Concurrent Programming">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/python-async-await-mastering-concurrent-programming/">Python Async Await: Mastering Concurrent Programming</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Python&#8217;s <code>async</code> and <code>await</code> are powerful features that enable you to write asynchronous code to improve the performance of your applications, particularly when dealing with I/O-bound and high-level structured network code.</p>



<p class="has-global-color-8-background-color has-background"><strong>Async and await</strong> are used with coroutines, which are special functions that can pause and resume their execution at specific points. <br><br>This allows <em><strong>multiple coroutines to run concurrently</strong></em> without the need for threads or complex synchronization. <br><br>To use the <code>async</code> and <code>await</code> keywords, you&#8217;ll first need to import the <code>asyncio</code> library, which provides the necessary framework for managing coroutines and the event loop.</p>



<h2 class="wp-block-heading">Let&#8217;s Start With a Fun Example: Asynchronous Coffee Shop</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="686" height="914" src="https://blog.finxter.com/wp-content/uploads/2023/09/image-71.png" alt="" class="wp-image-1651523" srcset="https://blog.finxter.com/wp-content/uploads/2023/09/image-71.png 686w, https://blog.finxter.com/wp-content/uploads/2023/09/image-71-225x300.png 225w" sizes="auto, (max-width: 686px) 100vw, 686px" /></figure>
</div>


<p>Imagine walking into a bustling coffee shop. Baristas are working at full speed, brewing multiple coffees simultaneously, while new customers keep walking in. This is a perfect scenario to understand the power of Python&#8217;s <code>async</code> and <code>await</code>.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="982" height="758" src="https://blog.finxter.com/wp-content/uploads/2023/09/async_await.gif" alt="" class="wp-image-1651522"/></figure>
</div>


<p>In our virtual coffee shop:</p>



<ol class="wp-block-list">
<li>Multiple customers can be served concurrently.</li>



<li>Each coffee takes a random amount of time to prepare, between 1 to 5 seconds.</li>



<li>Customers arrive at random intervals, every 1 to 3 seconds.</li>
</ol>



<p>Let&#8217;s break down the code:</p>



<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
import random

async def make_coffee(order_number):
    """Simulate making a coffee."""
    brew_time = random.randint(1, 5)
    print(f"Order {order_number}: Brewing coffee... (takes {brew_time} seconds)")
    await asyncio.sleep(brew_time)
    print(f"Order {order_number}: Coffee is ready!")

async def customer(order_number):
    """Simulate a customer ordering a coffee."""
    print(f"Order {order_number}: Customer arrived!")
    await make_coffee(order_number)

async def coffee_shop():
    """Simulate the coffee shop serving customers."""
    order_number = 1
    while True:
        await asyncio.gather(
            customer(order_number),
            asyncio.sleep(random.randint(1, 3))
        )
        order_number += 1

# Kickstart the simulation
asyncio.run(coffee_shop())
</pre>



<p><strong><code>make_coffee</code> Function</strong>: This simulates the brewing process. The <code>await asyncio.sleep(brew_time)</code> line mimics the time taken to brew a coffee. It&#8217;s asynchronous, so other tasks (like serving another customer) can run during this wait.</p>



<p><strong><code>customer</code> Function</strong>: Represents a customer&#8217;s arrival and their wait for coffee. The <code>await make_coffee(order_number)</code> line ensures that the customer waits for their coffee to be ready.</p>



<p><strong><code>coffee_shop</code> Function</strong>: This is the heart of our simulation. It uses <code>asyncio.gather</code> to handle both the arrival of a new customer and the brewing of coffee concurrently.</p>



<p>The beauty of this example is that it showcases how <code>async</code> and <code>await</code> can be used to handle multiple tasks concurrently, just like a real coffee shop. The baristas (our asynchronous functions) can brew multiple coffees at once, and new customers can arrive even if the previous ones haven&#8217;t been served yet.</p>



<h2 class="wp-block-heading">Understanding Coroutines</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="743" height="495" src="https://blog.finxter.com/wp-content/uploads/2023/09/image-229.png" alt="" class="wp-image-1651516" srcset="https://blog.finxter.com/wp-content/uploads/2023/09/image-229.png 743w, https://blog.finxter.com/wp-content/uploads/2023/09/image-229-300x200.png 300w" sizes="auto, (max-width: 743px) 100vw, 743px" /></figure>
</div>


<h3 class="wp-block-heading">Basics of Coroutines</h3>



<p>Coroutines are a key concept in Python&#8217;s asynchronous programming. They can help you write concurrent and non-blocking code, making your programs more efficient. </p>



<p>A coroutine is a special kind of function, similar to a <a href="https://blog.finxter.com/python-return-generator-from-function/">generator</a>, which can be paused and resumed during its execution.</p>



<p class="has-global-color-8-background-color has-background">In Python, coroutines are created with the <code>async def</code> syntax. When a coroutine is called, it returns a coroutine object, but it doesn&#8217;t start the execution of the function immediately. You can run the coroutine using the <code>await</code> keyword, which schedules it for execution in an event loop. When the coroutine is paused, it allows other coroutines to run in the meantime, creating a non-blocking, concurrent execution environment.</p>



<p>Here&#8217;s an example of a simple coroutine:</p>



<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_coroutine():
    print("Starting coroutine...")
    await asyncio.sleep(1)  # Pause the function for 1 second.
    print("Resuming coroutine...")
</pre>



<p>Notice the <code>async def</code> syntax for defining the coroutine and the use of the <code>await</code> keyword to pause the function&#8217;s execution.</p>



<h3 class="wp-block-heading">Coroutine with Async/Await Keywords</h3>



<p class="has-global-color-8-background-color has-background">With Python&#8217;s <code>async/await</code> syntax, you can write more readable and maintainable asynchronous code. The <code>async</code> keyword is used to define a coroutine function, while the <code>await</code> keyword is used to pause the execution of the coroutine and wait for another coroutine to complete. This syntax is preferred over the older <code>yield from</code> approach used with generators.</p>



<p>Here&#8217;s a comparison of using <a href="https://blog.finxter.com/understanding-generators-in-python/">generators</a> and the newer <code>async/await</code> syntax:</p>



<p><strong>Generators:</strong></p>



<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="">@asyncio.coroutine
def my_generator():
    yield from asyncio.sleep(1)
</pre>



<p><strong>Async/Await:</strong></p>



<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_coroutine():
    await asyncio.sleep(1)
</pre>



<p>As you can see, the <code>async/await</code> syntax is more concise and easier to understand. Remember that you can only use the <code>await</code> keyword inside an <code>async def</code> function. If you try to use it in a regular function, you&#8217;ll get a syntax error.</p>



<p></p>



<h2 class="wp-block-heading">Event Loops and Tasks</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="743" height="495" src="https://blog.finxter.com/wp-content/uploads/2023/09/image-230.png" alt="" class="wp-image-1651517" srcset="https://blog.finxter.com/wp-content/uploads/2023/09/image-230.png 743w, https://blog.finxter.com/wp-content/uploads/2023/09/image-230-300x200.png 300w" sizes="auto, (max-width: 743px) 100vw, 743px" /></figure>
</div>


<p>In this section, we&#8217;ll discuss event loops and tasks in Python&#8217;s <code><a href="https://blog.finxter.com/how-to-check-asyncio-package-version-in-python/">asyncio</a></code> library, focusing on asynchronous tasks, scheduling and resuming tasks, and timeouts in tasks.</p>



<h3 class="wp-block-heading">Asynchronous Tasks</h3>



<p class="has-global-color-8-background-color has-background">Asynchronous tasks, or coroutines, are the building blocks of concurrent programming in Python and are managed by an <strong>event loop</strong>. The event loop runs asynchronous tasks and callbacks, performs network I/O operations, and manages subprocesses, all within a single thread. To create a task, you&#8217;ll need to use the <code>asyncio.create_task()</code> function, like so:</p>



<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():
    # Your async code here

task = asyncio.create_task(my_coroutine())
</pre>



<p>This creates a <code>Task</code> object that represents the asynchronous execution of your coroutine.</p>



<h3 class="wp-block-heading">Scheduling and Resuming Tasks</h3>



<p class="has-global-color-8-background-color has-background">The event loop is responsible for scheduling and resuming tasks. When you create a task using <code>asyncio.create_task()</code>, the event loop schedules the task for execution. To allow other tasks to run concurrently, you should use the <code>await</code> keyword when calling other asynchronous functions. This will pause the current task and yield control back to the event loop, which then resumes the next available task.</p>



<p>For example, instead of using <code><a href="https://blog.finxter.com/python-sleep-for-less-than-a-second/">time.sleep()</a></code> to block your code, you should use <code>await asyncio.sleep()</code>, which allows other tasks to execute while your coroutine is &#8220;sleeping&#8221;:</p>



<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_coroutine():
    print("Starting task")
    await asyncio.sleep(5)
    print("Task complete")
</pre>



<p>If you need to run blocking code, you can use the <code>loop.run_in_executor()</code> function to run the code in a separate thread while allowing other async tasks to continue running:</p>



<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="">loop = asyncio.get_running_loop()
result = await loop.run_in_executor(None, blocking_function)
</pre>



<p></p>



<h2 class="wp-block-heading">Asynchronous Programming with Asyncio</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="743" height="499" src="https://blog.finxter.com/wp-content/uploads/2023/09/image-231.png" alt="" class="wp-image-1651518" srcset="https://blog.finxter.com/wp-content/uploads/2023/09/image-231.png 743w, https://blog.finxter.com/wp-content/uploads/2023/09/image-231-300x201.png 300w" sizes="auto, (max-width: 743px) 100vw, 743px" /></figure>
</div>


<h3 class="wp-block-heading">Understanding Asyncio.run() Function</h3>



<p class="has-global-color-8-background-color has-background">Asyncio is a powerful library in Python that allows you to write asynchronous code using the <code>async/await</code> syntax. The <code>asyncio.run()</code> function is the main entry point to run a coroutine. This function wraps the given <code>async</code> function with a call to <code>.run_until_complete()</code> and takes care of initializing and closing the event loop. When you want to execute an async function, you can use <code>asyncio.run()</code> to start it. </p>



<p>For example:</p>



<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():
    print("Hello, world!")

asyncio.run(main())
</pre>



<h3 class="wp-block-heading">Asyncio Sleep Method</h3>



<p class="has-global-color-8-background-color has-background">The <code>asyncio.sleep()</code> function is a convenient way to suspend the execution of a coroutine for a specified amount of time. This method takes a single argument, which represents the number of seconds to sleep. The <code>await</code> keyword is used to pause the coroutine while it&#8217;s waiting for the sleep to finish.</p>



<p>Here&#8217;s an example:</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="800" height="170" src="https://blog.finxter.com/wp-content/uploads/2023/09/image-70.png" alt="" class="wp-image-1651521" srcset="https://blog.finxter.com/wp-content/uploads/2023/09/image-70.png 800w, https://blog.finxter.com/wp-content/uploads/2023/09/image-70-300x64.png 300w, https://blog.finxter.com/wp-content/uploads/2023/09/image-70-768x163.png 768w" sizes="auto, (max-width: 800px) 100vw, 800px" /></figure>
</div>


<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 sleep_example():
    print("Start")
    await asyncio.sleep(1)
    print("Finish after 1 second")

asyncio.run(sleep_example())
</pre>



<p>In this example, the <code>await asyncio.sleep(1)</code> line suspends the execution of the <code>sleep_example()</code> coroutine for one second.</p>



<h3 class="wp-block-heading">Asyncio API Functions</h3>



<p class="has-global-color-8-background-color has-background">The asyncio API provides several functions to manage and schedule coroutines. <br><br>One of the most used API functions is <code>asyncio.gather()</code>. This function takes coroutines as arguments and returns a single coroutine that gathers the results of all the given coroutines. <br><br>When using <code>asyncio.gather()</code>, you can run multiple coroutines concurrently, which helps in improving the performance of your asynchronous code. </p>



<p>For example:</p>



<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 task_one():
    await asyncio.sleep(1)
    return "Task one completed."

async def task_two():
    await asyncio.sleep(2)
    return "Task two completed."

async def main():
    tasks = [task_one(), task_two()]
    results = await asyncio.gather(*tasks)
    print(results)

asyncio.run(main())
</pre>



<p>In this example, <code>task_one()</code> and <code>task_two()</code> run concurrently, thanks to the <code>asyncio.gather()</code> function. When both tasks are completed, the results are <a href="https://blog.finxter.com/print-python-list/">printed as a list</a>.</p>



<p>Remember to use the <code>async/await</code> keywords and the various functions provided by the <code>asyncio</code> package to make your Python code more efficient and responsive through asynchronous programming.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/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/" target="_blank" rel="noreferrer noopener">Python <code>__await()__</code> Magic Method</a></p>



<h2 class="wp-block-heading">Asynchronous Code and Concurrency</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="743" height="531" src="https://blog.finxter.com/wp-content/uploads/2023/09/image-232.png" alt="" class="wp-image-1651519" srcset="https://blog.finxter.com/wp-content/uploads/2023/09/image-232.png 743w, https://blog.finxter.com/wp-content/uploads/2023/09/image-232-300x214.png 300w" sizes="auto, (max-width: 743px) 100vw, 743px" /></figure>
</div>


<h3 class="wp-block-heading">The Role of the Event Loop</h3>



<p>In asynchronous programming, the event loop plays a crucial role in managing concurrent tasks. It is essentially a scheduler that allows your code to execute non-blocking I/O operations. When your code has to perform an I/O operation (like an <a href="https://blog.finxter.com/python-requests-library/">HTTP request</a>), the event loop lets the code keep running while waiting for the result. Once the I/O operation is complete, the event loop resumes the task.</p>



<p>The event loop is an essential component of the <code>asyncio</code> library in Python. This library provides a straightforward way to write asynchronous code using the <code>async/await</code> syntax. It serves as a foundation for many asynchronous Python frameworks, such as web servers and database connectors.</p>



<h3 class="wp-block-heading">Intro to Cooperative Multitasking</h3>



<p>Cooperative multitasking is a technique that allows multiple tasks to be executed concurrently by voluntarily yielding control to each other. In this approach, it is up to each task to give up control and allow other tasks to run.</p>



<p>In Python, you make use of cooperative multitasking by using asynchronous functions called coroutines. Coroutines are declared using the <code>async def</code> syntax and await other coroutines using the <code>await</code> keyword. When a coroutine awaits another coroutine, it temporarily suspends its execution, allowing other tasks to run in the meantime.</p>



<p>Here&#8217;s a simple example using <code>asyncio</code>:</p>



<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 wait_and_print(message, delay):
    await asyncio.sleep(delay)
    print(message)

async def main():
    await asyncio.gather(
        wait_and_print("Hello, world!", 1),
        wait_and_print("Asyncio is awesome!", 2)
    )

asyncio.run(main())
</pre>



<h3 class="wp-block-heading">Concurrency in Python</h3>



<p>Python offers various approaches to dealing with concurrency, such as threading, multiprocessing, and asynchronous programming. Asynchronous programming with <code>asyncio</code> is particularly suitable for I/O-bound tasks, such as making HTTP requests or querying databases.</p>



<p>Through asynchronous programming, Python can manage concurrency without the need for parallelism. This is achieved by interleaving the execution of tasks using event loops and cooperative multitasking. While true parallelism requires multiple cores, concurrency through asynchronous programming can be achieved on single-core systems by efficiently utilizing the available resources.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/python-cheat-sheet/" target="_blank" rel="noreferrer noopener">Python Beginner Cheat Sheet: 19 Keywords Every Coder Must Know</a></p>



<h2 class="wp-block-heading">Advanced Concepts and Applications</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="743" height="546" src="https://blog.finxter.com/wp-content/uploads/2023/09/image-234.png" alt="" class="wp-image-1651520" srcset="https://blog.finxter.com/wp-content/uploads/2023/09/image-234.png 743w, https://blog.finxter.com/wp-content/uploads/2023/09/image-234-300x220.png 300w" sizes="auto, (max-width: 743px) 100vw, 743px" /></figure>
</div>


<h3 class="wp-block-heading">Asynchronous Generators</h3>



<p class="has-global-color-8-background-color has-background"><a href="https://blog.finxter.com/python-async-with-statement-simplifying-asynchronous-code/">Asynchronous generators</a> are a powerful feature in async-await programming. They allow you to create generator functions which can produce a series of results while asynchronously waiting for other operations to complete. To create an asynchronous generator, you simply need to add the <code>async def</code> keyword before the function and use <code>await</code> when necessary. </p>



<p>For example:</p>



<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 async_generator():
    for i in range(5):
        await asyncio.sleep(1)
        yield i
</pre>



<p>This generator would produce values from 0 to 4, with a 1-second delay between each yield. To consume the results, use the <code>async for</code> statement:</p>



<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 for value in async_generator():
    print(value)
</pre>



<h3 class="wp-block-heading">Understanding Threading</h3>



<p>In the context of async-await, understanding threading is crucial. Traditional threading can create issues with shared variables and resources, leading to difficult-to-debug problems. However, in async-await programming, there is generally only one thread, making it inherently safer. </p>



<p>You can think of async-await as a cooperative multitasking approach, where the tasks voluntarily yield control to one another when waiting for resources or operations to complete. This allows you to achieve concurrency without dealing with the complexities of thread management.</p>



<h3 class="wp-block-heading">Dealing with Latency</h3>



<p>Network latency can cause delays and slow down your application. Async-await is an effective solution to dealing with latency, as it allows you to keep the flow of your program moving even when certain tasks face delays due to network or resource constraints.</p>



<p>For example, assume you need to make several web requests to fetch data. Instead of waiting for each request to complete before starting the next, async-await enables you to initiate all requests simultaneously, significantly decreasing the total time spent waiting.</p>



<p>In a similar fashion, async-await can also be leveraged to process database queries, file I/O, and other high-latency operations.</p>



<h3 class="wp-block-heading">Introspection in Asyncio</h3>



<p>Introspection is the mechanism that allows you to examine current tasks, coroutines, and other aspects of the event loop, aiding in understanding and debugging your program. Asyncio, the Python library that provides asynchronous concurrency, offers several introspection tools.</p>



<p>For example, <code>asyncio.all_tasks(loop=None)</code> <a href="https://blog.finxter.com/python-return-set-from-function/">returns a set</a> of all currently scheduled tasks in the specified loop (or the default loop if not specified). This allows you to track the progress of tasks, identify bottlenecks, and gain insight into the overall health of your program. </p>



<p>Additionally, other introspection methods include <code>asyncio.current_task(loop=None)</code> and <code>asyncio.Task.get_stack(*, limit=None)</code> allowing for detailed analysis of task states and traceback information, respectively.</p>



<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended</strong>: <a href="https://blog.finxter.com/python-async-function/">Python Async Function</a></p>



<h2 class="wp-block-heading">Frequently Asked Questions</h2>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="500" height="750" src="https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-3250614.jpeg" alt="" class="wp-image-1651466" srcset="https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-3250614.jpeg 500w, https://blog.finxter.com/wp-content/uploads/2023/09/pexels-photo-3250614-200x300.jpeg 200w" sizes="auto, (max-width: 500px) 100vw, 500px" /></figure>
</div>


<h3 class="wp-block-heading">How does async/await work with Python&#8217;s asyncio?</h3>



<p>Async/await works in conjunction with Python&#8217;s asyncio library to handle concurrency in a more efficient and simpler way. They allow you to define asynchronous code as coroutines, which can pause their execution instead of blocking the entire program. </p>



<p>When a coroutine encounters an <code>await</code> expression, it yields control back to the event loop, allowing other tasks to run in the meantime. You can use <code>asyncio.run()</code> to run a coroutine or combine multiple coroutines with <code>asyncio.gather()</code>. </p>



<p>Find more about it <a href="https://stackabuse.com/python-async-await-tutorial/">in this tutorial</a>.</p>



<h3 class="wp-block-heading">What are the benefits of async/await over threading in Python?</h3>



<p>Async/await provides some advantages over threading, including lower memory overhead, better performance with large numbers of I/O-bound tasks, and easier debugging. </p>



<p>Additionally, async/await is more Pythonic while dealing with concurrency and offers a more readable syntax. </p>



<p>However, it&#8217;s important to note that async/await is most effective for I/O-bound workloads, whereas threading is more suitable for CPU-bound tasks. </p>



<p>Learn more about <a href="https://realpython.com/async-io-python/">Async IO in Python</a>.</p>



<h3 class="wp-block-heading">How can I use Python&#8217;s requests library with async/await?</h3>



<p>The <code>requests</code> library is not designed for async/await usage, but you can use the <code>httpx</code> library, which provides a similar API but with async/await support. To use <code>httpx</code>, install it via <code>pip</code>, then use the <code>async</code> and <code>await</code> keywords alongside <code>httpx</code> methods like <code>httpx.get()</code> or <code>httpx.post()</code>. </p>



<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Don&#8217;t forget to wrap your code in <code>async def</code> functions and run them using the asyncio event loop.</p>



<h3 class="wp-block-heading">What is the difference between a Python coroutine and an async function?</h3>



<p>A Python coroutine is a function that can pause its execution and resume later, allowing other tasks to run in the meantime. They are defined using the <code>async def</code> syntax. </p>



<p>On the other hand, an async function is simply a function that has been declared with the <code>async</code> keyword. All async functions are coroutines, but not all coroutines are specifically async functions. </p>



<p>You can find more information about the <a href="https://www.pythontutorial.net/python-concurrency/python-async-await/">Python coroutines and async functions</a> here.</p>



<h3 class="wp-block-heading">How can I run multiple async tasks concurrently in Python?</h3>



<p>To run multiple async tasks concurrently, you can use the <code>asyncio.gather()</code> function. This function takes a list of coroutines as its arguments and returns an awaitable object that can be used with the <code>await</code> keyword. </p>



<p>When you await the result of <code>asyncio.gather()</code>, all the given coroutines will be scheduled to run concurrently, and the results will be returned in the same order as the input coroutines. </p>



<p>Remember that you need to use an asyncio event loop to run your async tasks, like <code>asyncio.run()</code>.</p>



<h3 class="wp-block-heading">What is the use of asynchronous context managers in Python?</h3>



<p>Asynchronous context managers are useful for managing resources in an asynchronous environment, such as when you use <code>async with</code> statement. </p>



<p>They ensure proper acquisition and release of resources in a non-blocking manner, making your code more efficient, and preventing issues like resource leaks or deadlocks. </p>



<p>Examples of asynchronous context managers include opening and closing files, connecting to databases, or using an HTTP client. </p>





<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="743" height="575" src="https://blog.finxter.com/wp-content/uploads/2023/09/image-233.png" alt="" class="wp-image-1651515" srcset="https://blog.finxter.com/wp-content/uploads/2023/09/image-233.png 743w, https://blog.finxter.com/wp-content/uploads/2023/09/image-233-300x232.png 300w" sizes="auto, (max-width: 743px) 100vw, 743px" /></figure>
</div>


<p class="has-base-2-background-color has-background"><img src="https://s.w.org/images/core/emoji/17.0.2/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/">Python Async With Statement — Simplifying Asynchronous Code</a></p>
<p>The post <a href="https://blog.finxter.com/python-async-await-mastering-concurrent-programming/">Python Async Await: Mastering Concurrent Programming</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: blog.finxter.com @ 2026-07-04 08:14:48 by W3 Total Cache
-->