syncwrap is a light and elegant solution for running asynchronous functions in a synchronous environment. This helper neatly packages your async tasks, handling event loop creation and cleanup so you don’t have to.
import asyncio
def run_async_safely(async_func, *args, **kwargs):
"""
Executes an asynchronous function within a new event loop.
This helper function creates a new event loop for each call,
ensuring that your asynchronous code can run safely in a synchronous
context without interfering with other parts of your application.
Parameters:
async_func: The asynchronous function to execute.
*args, **kwargs: Arguments to pass to the async function.
Returns:
The result of the asynchronous function.
"""
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
return loop.run_until_complete(async_func(*args, **kwargs))
finally:
loop.close()
# Example usage:
async def greet(name):
await asyncio.sleep(1) # Simulate an asynchronous operation
return f"Hello, {name}!"
if __name__ == "__main__":
message = run_async_safely(greet, "World")
print(message)
The run_async_safely
function is designed to bridge the gap between asynchronous and synchronous code. Each time it is called, a new event loop is created and set as the current loop, which isolates the async operation and prevents potential conflicts with any existing event loop. Once the asynchronous function completes its task, the event loop is properly closed to free up resources.
In the example provided, the greet
function is an asynchronous function that simulates a brief pause before returning a greeting. By wrapping it with run_async_safely
, you can call it from a regular, synchronous script without additional overhead.
syncwrap is ideal for small scripts or one-off tasks where you need to integrate asynchronous operations into a synchronous workflow. For larger applications with extensive asynchronous requirements, managing the event loop manually might offer more flexibility, but for many cases, syncwrap provides a clean and graceful solution.
Enjoy using syncwrap to keep your asynchronous code organized and accessible. Happy coding!