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()
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Ardhi
  • 2,855
  • 1
  • 22
  • 31
  • 3
    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
  • I redirected the existing duplicate link to the canonical, but it's inappropriate. The original duplicate was also clearly about recursion, and this question is not. – Karl Knechtel Aug 13 '22 at 12:56
  • This should probably be considered as a typo, since OP already understands how to use `return` (in `testAsync`). But the underlying question seems to be about how to get the information out of `syncFunc` when calling it, and the natural way to do that is... with `return`, so there we go - I used that duplicate instead. – Karl Knechtel Aug 13 '22 at 13:01

2 Answers2

3

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
  • 36,989
  • 16
  • 116
  • 159
-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,855
  • 1
  • 22
  • 31