2

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()

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Calling bar from a notebook will fail ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.