1

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()
Ardhi
  • 2,535
  • 20
  • 28
  • 2
    Python functions return `None` by default. Add a `return` to `syncFunc` and you'll get your result. – dirn Jun 06 '20 at 14:10
  • yes (facepaml myself). I thought it was async specific problem. Thank you! – Ardhi Jun 06 '20 at 14:23

2 Answers2

2

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)
Mikhail Gerasimov
  • 32,558
  • 15
  • 103
  • 148
-1

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.

Ardhi
  • 2,535
  • 20
  • 28