Programming Search⌘K

Featurecore

Coroutines with async and await

Also called async def, await, coroutine, coroutine function, awaitable, __await__, native coroutine, PEP 492.

async def defines a coroutine function. A call makes a coroutine object and runs nothing; await suspends the coroutine until an awaitable is done. An event loop such as asyncio drives coroutines.

Language
Python
Proposals
pep-492

Synopsis

import asyncio

async def greet(name):
    await asyncio.sleep(0)
    return f"hello, {name}"

print(asyncio.run(greet("Ada")))
Output
hello, Ada

Semantics

r1. "Functions defined with async def syntax are always coroutine functions, even if they do not contain await or async keywords."1 Example: call-makes-object.

r2. Calling a coroutine function returns a coroutine object and runs none of its body. "Note that simply calling a coroutine will not schedule it to be executed". asyncio.run(), an await, or a task runs it.2

r3. await will "Suspend the execution of coroutine on an awaitable object. Can only be used inside a coroutine function."3 "It is a SyntaxError to use await outside of an async def function".4 "It is a SyntaxError to use a yield from expression inside the body of a coroutine function."1 Example: await-outside.

r4. An awaitable "generally implements an await() method" that "Must return an iterator". "Coroutine objects returned from async def functions are awaitable."5 Example: custom-awaitable.

r5. A coroutine runs as its __await__() iterator is advanced. "When the coroutine has finished executing and returns, the iterator raises StopIteration, and the exception’s value attribute holds the return value."5

r6. coroutine.send(value) "Starts or resumes execution of the coroutine." throw() raises an exception at the point where it is suspended, and close() makes it "clean itself up and exit".5

r7. "unlike generators, coroutines do not directly support iteration." "It is a RuntimeError to await on a coroutine more than once."5 Example: await-twice.

r8. "The language doesn’t place any restriction on the type or value of the objects yielded by the iterator returned by await". Their meaning belongs to the framework that drives the coroutines, such as asyncio.5

Examples

import inspect

async def fetch():
    print("running")
    return 1

print(inspect.iscoroutinefunction(fetch))
coro = fetch()
print(type(coro).__name__)
coro.close()
Output
True
coroutine

The call made a coroutine object, but "running" is never printed (rule r2). close() marks the coroutine as finished, so Python gives no warning about it.

class Ticket:
    def __await__(self):
        value = yield "waiting for a value"
        return value

async def use():
    got = await Ticket()
    return got * 2

coro = use()
print(coro.send(None))
try:
    coro.send(21)
except StopIteration as stop:
    print("returned", stop.value)
Output
waiting for a value
returned 42

This program drives a coroutine by hand, as an event loop does. The first send(None) runs use up to the yield inside Ticket.__await__, and the yielded value comes out. The second send resumes the coroutine with 21, and the return value arrives in StopIteration.value (rules r4 to r6).

import asyncio

async def step(name):
    print("start", name)
    await asyncio.sleep(0)
    print("end", name)

async def main():
    await step("a")
    await step("b")

asyncio.run(main())
Output
start a
end a
start b
end b

Each await waits until its coroutine is done, so two awaits in a row run one after the other. To run coroutines at the same time, make tasks; see The asyncio module.

Pitfalls

This code raises RuntimeError, on purpose.

import asyncio

async def value():
    return 1

async def main():
    coro = value()
    print(await coro)
    print(await coro)

asyncio.run(main())

A coroutine object runs once (rule r7). To run the work again, call the coroutine function again.

This code raises SyntaxError, on purpose.

import asyncio

def main():
    await asyncio.sleep(0)

await is allowed only in a coroutine function (rule r3). The fix is async def main():.

This code runs but gives a wrong answer on purpose.

import asyncio

async def total():
    return 42

async def main():
    result = total()          # no await
    print(type(result).__name__)
    result.close()

asyncio.run(main())
Output
coroutine

Without await, result is a coroutine object, not 42. If such an object is never awaited, asyncio warns: "RuntimeWarning: coroutine 'test' was never awaited", for a coroutine function named test. "The usual fix is to either await the coroutine or call the asyncio.create_task() function".6

Comparison

Coroutines have send(), throw() and close(), which are "analogous to those of generators", but a coroutine is not an iterator (rule r7).5 PEP 492 chose the words async and await because "async/await is not a new concept in programming languages". It names C#, a proposal for ECMAScript 7, Hack, Dart and Scala, and says that the shared syntax "makes working with many languages in one project easier".4 In Python, the language gives only the syntax and the protocol; the event loop comes from a library (rule r8).

References

  1. The Python Language Reference, Python 3.15, 8.9 Coroutines; 8.9.1 Coroutine function definition
  2. Coroutines and Tasks, Python 3.15 documentation, Coroutines
  3. The Python Language Reference, Python 3.15, 6.4 Await expression
  4. PEP 492: Coroutines with async and await syntax, Specification; Why “async” and “await” keywords
  5. The Python Language Reference, Python 3.15, 3.4.1 Awaitable Objects; 3.4.2 Coroutine Objects
  6. Developing with asyncio, Python 3.15 documentation, Detect never-awaited coroutines

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source