Meaning
Defines an asynchronous function (coroutine) that can be awaited to perform non‑blocking operations, typically I/O‑bound work such as network requests or file access.
Primary Function
Asynchronous function definition
Communicative Purpose
Create a coroutine that yields control back to the event loop while waiting for external events.
Pattern
async def function_name(parameters): ...
Core Structure
async def ...(...): ...
Função primária
Asynchronous function definition
Propósito comunicativo
Create a coroutine that yields control back to the event loop while waiting for external events.
Situações de gatilho
When making HTTP requests with aiohttp, reading/writing files with aiofiles, or any code that needs to run concurrently without blocking the event loop.
Contextos
Asyncio‑based applications, web frameworks like FastAPI or aiohttp, scripts using asyncio.run, and libraries that expose async APIs.
Padrão
async def function_name(parameters): ...
Estrutura central
async def ...(...): ...
Slots de substituição
function_name: identifier for the coroutine; parameters: comma‑separated list of arguments (may be empty); body: indented block containing await expressions or other async code.
Colocados típicos
- await
- asyncio.gather
- async with
- async for
- asyncio.create_task
Substituições comuns
- def function_name(params): (synchronous version)
- lambda: anonymous function
- functools.partial for partial application
Erros comuns
Calling the async function without await (returns a coroutine object); forgetting to await inner coroutines; mixing blocking code inside the coroutine; omitting the colon or incorrect indentation.
Similar / contraste
def function_name(params): (regular synchronous function); lambda: anonymous function; @staticmethod / @classmethod decorators on methods
Interferências
Coming from JavaScript: confusing async def with returning a Promise; coming from Java/C#: assuming async def starts a new thread rather than a coroutine.
Família do chunk
- async/await patterns
- async context managers
- async iterators
Nuance
The function returns a coroutine object; it must be awaited or scheduled via asyncio.create_task/event loop to actually run. If the body contains no await expressions, it still returns a coroutine that runs sequentially.
Efeito pragmático
Enables non‑blocking I/O and concurrent execution within a single thread, improving responsiveness and throughput.
Dica de memória
Think ‘async def’ as ‘asynchronous definition’ – the gateway to awaitable code.
Nota
The async def syntax replaced the @asyncio.coroutine decorator with yield from pattern, which was deprecated in Python 3.8 and removed in 3.11. Every async def function returns a coroutine object even if it contains no await expressions.
Upgrade path
Use asyncio.gather to run multiple coroutines concurrently: await asyncio.gather(fetch_data(), fetch_data())
Log in to save chunks.