1

If I need to call some synchronous code from a coroutine, does it matter if I use a coroutine for that synchronous code?

Example: Does it matter if I use get_hello or coro_get_hello? And if not, what is the correct / preferred way?

import asyncio
import re


class Foo:
    def get_hello(self, string):
        return re.findall(r"(H.+?)\n", string)

    async def coro_get_hello(self, string):
        return re.findall(r"(H.+?)\n", string)

    async def worker(self):
        my_string = "Hello\nWorld\n" * 200
        for _ in range(5):
            print(await self.coro_get_hello(my_string))
            print(self.get_hello(my_string))
            await asyncio.sleep(1)

    def start(self):
        asyncio.run(self.worker())


if __name__ == "__main__":
    Foo().start()```
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sansch
  • 61
  • 1
  • 5
  • No, it doesn't help. If you're worried about blocking the event loop, you need to either switch to an asynchronous solution, or do your blocking operation in another thread/process. – Patrick Haugh Jan 31 '20 at 15:18

1 Answers1

1

Main point of using async def / await is to explicitly mark places in a code where context switch can happen (where execution flow can switch to another coroutine). Lesser such places - easier to handle a concurrent code. Thus don't make a function coroutine unless you have some reason for it.

What reason do you have to make a function coroutine?

  • If this function would need to await some coroutine, it should be a coroutine either
  • If the function would need to await some Future or other async object, it should be defined a coroutine
  • If the function doesn't need to await for something, but it will be called inside other coroutine and calling the function takes much time. In this case it makes sense to call a function in a thread asynchronously and await the thread is finished.

You can read a bit more about it here (and in discussion under the answer).

Mikhail Gerasimov
  • 36,989
  • 16
  • 116
  • 159