Python Glossary Русский

Python 3.5+Async programmingterm

async def / await

coroutines

async def declares a coroutine. await suspends execution until another coroutine produces its result.

Syntax

async def name() -> T:
    result = await other_coroutine()

Calling greet('Alice') without await runs nothing — it just builds a coroutine object, and at exit you get the warning that a coroutine was never awaited. await itself is only legal inside async def, and the top of the program is started with asyncio.run(main()). Also, async is not parallelism: the event loop is a single thread, so one ordinary blocking call such as time.sleep() or synchronous requests freezes every task at once.

Examples

import asyncio
async def greet(name):
    await asyncio.sleep(0)
    return f'hello, {name}'
async def main():
    msg = await greet('Alice')
    print(msg)  # → hello, Alice
asyncio.run(main())
# Корутина без await не выполняется: вызов лишь создаёт объект
async def f():
    return 1
coro = f()
print(type(coro).__name__)  # → coroutine
coro.close()  # иначе RuntimeWarning: coroutine was never awaited

See also

Open in the full glossarydocs.python.orgReport an inaccuracy