How To Run a Function Alongside an Async One in Python

QASource Engineering Team | December 23, 2024

How To Run a Function Alongside an Async One in Python

Use the asyncio library, which provides tools to handle asynchronous operations, to run a function alongside an async one in Python. Here’s how you can handle this situation, depending on whether the function you want to run is synchronous or asynchronous:

import asyncio

# Example synchronous function
def sync_function():
	for i in range(5):
    	print(f"Synchronous Function: {i}")
    	import time
    	time.sleep(1)

# Example asynchronous function
async def async_function():
	for i in range(5):
    	print(f"Asynchronous Function: {i}")
    	await asyncio.sleep(1)

async def main():
	# Run the synchronous function in a separate thread alongside the async one
	await asyncio.gather(
    	async_function(),
    	asyncio.to_thread(sync_function)
	)

asyncio.run(main())

This ensures the optimal use of Python’s async capabilities, whether dealing with synchronous or asynchronous code.

Final Words

By combining asyncio.gather() and asyncio.to_thread(), you can seamlessly run synchronous functions alongside asynchronous ones without blocking the event loop. This approach is beneficial when integrating legacy synchronous code or performing inherently blocking tasks (e.g., file I/O or CPU-intensive operations). Leveraging these tools helps you make optimal use of Python’s asynchronous capabilities, keeping your applications responsive and efficient.

Disclaimer

This publication is for informational purposes only, and nothing contained in it should be considered legal advice. We expressly disclaim any warranty or responsibility for damages arising out of this information and encourage you to consult with legal counsel regarding your specific needs. We do not undertake any duty to update previously posted materials.

Post a Comment

Categories