Meaning
Schedules the given coroutine to run concurrently as a Task and returns the Task object.
Primary Function
Schedules a coroutine for concurrent execution and returns a Task that can be awaited or cancelled.
Communicative Purpose
Indicates the intention to run a coroutine in the background without blocking the current coroutine.
Pattern
asyncio.create_task(<coroutine>)
Core Structure
asyncio.create_task(<coroutine>)
Função primária
Schedules a coroutine for concurrent execution and returns a Task that can be awaited or cancelled.
Propósito comunicativo
Indicates the intention to run a coroutine in the background without blocking the current coroutine.
Situações de gatilho
When you need to launch a coroutine to run alongside other code, e.g., starting background tasks, fire‑and‑forget operations, or launching multiple concurrent operations.
Contextos
Inside any async function or method that is already running inside an asyncio event loop; typical in asyncio‑based applications, web servers, or any asyncio‑driven code.
Padrão
asyncio.create_task(<coroutine>)
Estrutura central
asyncio.create_task(<coroutine>)
Slots de substituição
{"my_coroutine": "any awaitable coroutine object (e.g., my_coro(), fetch_data())"}
Colocados típicos
- {"keyword":"await"} {"keyword":"task"} {"keyword":"cancel"} {"keyword":"result"} {"keyword":"exception"} {"keyword":"gather"} {"keyword":"ensure_future"}
Substituições comuns
- asyncio.ensure_future(<coroutine>) loop.create_task(<coroutine>)
Erros comuns
Failing to await or retain the returned Task, leading to "Task was destroyed but it is pending!" warnings Not handling exceptions raised inside the coroutine Calling create_task outside of a running event loop (raises RuntimeError) Confusing create_task with ensure_future and missing the explicit Task benefits
Similar / contraste
asyncio.ensure_future loop.create_task asyncio.gather asyncio.wait
Interferências
Confusing create_task with ensure_future can lead to subtle differences in loop handling; using create_task outside a running loop raises RuntimeError. Not keeping a reference to the Task may cause it to be garbage‑collected before completion, producing a warning.
Família do chunk
- asyncio-concurrency
Nuance
create_task schedules the coroutine to run soon but does not await it; the returned Task can be awaited later, cancelled, or inspected for results/exceptions.
Efeito pragmático
Signals that the coroutine should run concurrently, allowing the current coroutine to continue without blocking.
Dica de memória
Fire‑and‑forget a coroutine with create_task.
Nota
Preferred over asyncio.ensure_future starting with Python 3.7 because it explicitly creates a Task and conveys clearer intent.
Upgrade path
Prefer asyncio.create_task over asyncio.ensure_future for clarity and better task management in Python 3.7+.
Log in to save chunks.