Search code examples
pythonmultithreadingasynchronousasync-awaitpython-asyncio

asyncio.run inside sync function returning None


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

Solution

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