async — Expert Examples
Declares an asynchronous coroutine function or context manager
Async internals: coroutine objects
Examining async functions under the hood.
python
import asyncio import inspect import dis async def example(): await asyncio.sleep(0) return 42 # Coroutine object coro = example() print(f"Type: {type(coro)}") print(f"Is coroutine: {inspect.iscoroutine(coro)}") print(f"State: {inspect.getcoroutinestate(coro)}") # Must close or run it coro.close() # Bytecode print(f"\nBytecode:") dis.dis(example) # async def compiles similarly to regular def # but the code object has CO_COROUTINE flag print(f"\nFlags: {example.__code__.co_flags}") print(f"Is coroutine func: {inspect.iscoroutinefunction(example)}")
async def sets the CO_COROUTINE flag on the code object. The bytecode uses GET_AWAITABLE and SEND to implement await. Coroutine objects track their state (created, running, suspended, closed).
Want to try these examples interactively?
Open Expert Playground