1

Recently I'm looking into python asyncio and coroutines, I've understood the event loop and I'm successfully using async implemented libraries with the syntax await/async using FASTAPI as a framework for building REST APIs.

Now, I need to use a library which has not been developed asynchronously, and which contains a lot of I/O bound functions (to binary connect to a custom server and do some proprietary logic).

I would like to make some function calls of this library async, but I'm not sure what should be the correct way to transform a generic function in a coroutine, and if it makes sense at all.

So far I'm just wrapping the function in this way:

import asyncio

async def my_function():
    await asyncio.get_event_loop().run_in_executor(None, the_library_sync_function)

Is that the correct way to make a function awaitable? Are there any drawbacks? Am I getting it right?

Thank you

edoedoedo
  • 1,469
  • 2
  • 21
  • 32
  • 1
    Check out: 1. [How can I wrap a synchronous function in an async coroutine?](https://stackoverflow.com/questions/43241221/how-can-i-wrap-a-synchronous-function-in-an-async-coroutine), and 2. [How do we call a normal function where a coroutine is expected?](https://stackoverflow.com/questions/38557768/how-do-we-call-a-normal-function-where-a-coroutine-is-expected) – DarrylG Dec 09 '21 at 16:06
  • Python 3.10 added the function `to_sleep` to asyncio. Its implementation is simple and similar to yours. It's basically a wrapper around `run_in_executor(None, function)`. – Paul Cornelius Dec 09 '21 at 20:16
  • @PaulCornelius I guess you mean `asyncio.to_thread` – thisisalsomypassword Dec 10 '21 at 08:41
  • Yes, I meant to_thread. – Paul Cornelius Dec 10 '21 at 22:47

0 Answers0