Skip to main content

Posts

Showing posts from 2022

Executing asynchronous coroutine (asyncio) synchronously in Python

I worked a lot with async functions in languages other than Python. It's usually very straight-forward and easy to find any answers in internet. It was a surprise that solving a very simple question regarding async in Python took me a day. How to execute an async coroutine in a classic synchronous function? Async library author's position and CPython's GIL made execution of async functions synchronously harder than required. Instead of an exact answer dozens of answers on StackOverflow explain why it is not possible or a bad idea (and a handful of not working suggestions). Ok-ok, I just need a solution! I had to understand how asyncio works to solve this. So, this code allows to synchronously wait for execution completion of async coroutine without a hot spin-lock: def sync_exec ( coroutine : Awaitable ) -> Any :     try :         asyncio . get_running_loop ()     except RuntimeError :         loop = asyncio . new_event_loop ()         return loop . run_until_complet