0

Python coroutine created with 'async' keyword (Python 3.5+) can be awaited, however, the outer most one can't be awaited as Python says "SyntaxError: 'await' outside function"

import asyncio as aio

async def f():
    print(1)
    await aio.sleep(3)
    print(2)
    return 3

print(await f())

How to 'await' the 'f' function in the example above?

2 Answers 2

2

If you use Python 3.7+, the syntax is even simpler (no need to manually create a loop etc.):

import asyncio as aio

async def f():
    print(1)
    await aio.sleep(3)
    print(2)
    return 3

print(aio.run(f())
Sign up to request clarification or add additional context in comments.

Comments

0

It's not possible to await at global scope, instead, run an event loop as below:

import asyncio as aio

async def f():
    print(1)
    await aio.sleep(3)
    print(2)
    return 3

def fdone(r):
    print(r.result())

loop = aio.get_event_loop()
t = loop.create_task(f())
t.add_done_callback(fdone)
loop.run_until_complete(t)
print(4)

1 Comment

A simpler print(loop.run_until_complete(f())) would work just as well, asrun_until_complete() will automatically create the task. You don't need add_done_callback because run_until_complete() returns the result of the awaitable it received.

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.