0

Suppose I have normal sync function that gets called a lot in my async application. Does it make any difference if I simply define it as an async function so I can await it, but I don't change its code at all?

lufte
  • 1,283
  • 1
  • 11
  • 21
  • 1
    If your function doesn't contain any async code, it usually makes no sense to make this function async. Just leave it regular. As long at it doesn't take much time to execute (and through that doesn't block event loop) just call function regularly in async code. Otherwise use [executor](https://docs.python.org/3/library/asyncio-eventloop.html#executing-code-in-thread-or-process-pools) to avoid blocking event loop. [More detailed answer](https://stackoverflow.com/a/33399896/1113207). – Mikhail Gerasimov Nov 14 '18 at 07:07

1 Answers1

3

It doesn't make a (semantic) difference, a coroutine that doesn't await is still a perfectly valid coroutine that can itself be awaited, passed to asyncio.run, asyncio.create_task, asyncio.gather, and so on.

You might want to add a comment to make it clear to the reader that the function doesn't actually contain any blocking code.

For example, the following code:

while some_condition:
    await coroutine_without_await()

This code blocks the event loop for as long as the while loop lasts, regardless of the presence of an await.

user4815162342
  • 141,790
  • 18
  • 296
  • 355