asyncio.run inside sync function returning None

Question:

Sorry if seems basic, but I really don’t understand why this returns None:

import asyncio

def syncFunc():
    async def testAsync():
        return 'hello'
    asyncio.run(testAsync())

# in a different file:
x = syncFunc()
print(x)
# want to return 'hello'

how to return ‘hello’ from asyncio.run?

this works but not what I want:

def syncFunc():
    async def testAsync():
         print('hello')
    asyncio.run(testAsync())

syncFunc()
Asked By: Ardhi

||

Answers:

I can do it like this, breaking down the asyncio.run() function :

def syncFunc():
    async def testAsync():
        return 'hello'
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    result = loop.run_until_complete(testAsync())
    return result

x = syncFunc()
print(x)

shows ‘hello’.

but the underlying machinery of asyncio.run() remains a mystery.

Answered By: Ardhi

why this returns None:

Because in your code syncFunc function doesn’t have return statement.
Here’s slightly different version that will do what you want:

def syncFunc():
    async def testAsync():
        return 'hello'
    return asyncio.run(testAsync())  # return result of asyncio.run from syncFunc

# in a different file:
x = syncFunc()
print(x)
Answered By: Mikhail Gerasimov