NoRaincheck

Syncify Python Async Functions

Syncify Python Async Functions

April 2025

There’s a lot to unpack with Python shenanigans. Including why nest-asyncio even exists. Here is yet another pattern (note: you really should look into https://asyncer.tiangolo.com/ if it fits for you).

1def syncify(func, *args, **kwargs):
2    def wrapper(coro):
3        return asyncio.run(coro)
4
5    with ThreadPoolExecutor(max_workers=1) as executor:
6        result = next(executor.map(wrapper, [func(*args, **kwargs)]))
7    return result

Which delegates/moves the execution to a threadpool to bypass potential issues. This is definitely not a ‘performant’ option, but it may save your skin.

I’ll point out in general, where your event loop is not nested, you could just use asyncio.run.

<< Previous Post

|

Next Post >>

🎲 Random post

|

All posts

#Python #Async