zapta
zapta

Reputation: 125

How to call an async python function from a non async function

I have a Python function that must be synchronous (non async) that needs to call an async function. Any way of doing it?

Motivation: async foo() is provided by a communication package and bar() is a callback of a GUI framework so I don't have control over their synchronicity but need to bridge the gap, having bar calling foo and using its returned value.

async def foo():
   return 'xyz'


def bar():
   value = ... foo()

Upvotes: 2

Views: 1872

Answers (1)

isaactfa
isaactfa

Reputation: 6651

You can use asyncio.run to run a coroutine synchronously:

import asyncio

async def foo():
    return 'xyz'

def bar():
    xyz = asyncio.run(foo())
    print(xyz)

Upvotes: 3

Related Questions