Meaning
Schedules a coroutine to run concurrently as a Task on the given event loop, returning the Task object. This allows the coroutine to start executing without blocking the current flow, and the task can be awaited or cancelled later.
Primary Function
Concurrency / Task management
Communicative Purpose
Launch asynchronous execution without blocking the current flow.
Pattern
loop.create_task(coro())
Core Structure
loop.create_task(...)
Função primária
Concurrency / Task management
Propósito comunicativo
Launch asynchronous execution without blocking the current flow.
Situações de gatilho
Async applications: starting background work without blocking the caller; Concurrent pipelines: firing off multiple coroutines to run in parallel; Legacy integration: bridging async code with callback-based APIs
Contextos
Asyncio-based Python applications, web servers using aiohttp, GUI apps with async loops.
Padrão
loop.create_task(coro())
Estrutura central
loop.create_task(...)
Slots de substituição
coro: async function; coro() must return a coroutine object
Colocados típicos
- await asyncio.gather()
- loop.run_until_complete()
- async/await syntax
Substituições comuns
- asyncio.create_task(my_coro()) (Python 3.7+)
- ensure_future(my_coro())
Erros comuns
Forgetting to await the task later → unawaited coroutine warning and silent task failure; Passing a non-coroutine object such as a regular function → TypeError at call site; Creating tasks without retaining a reference → task garbage-collected mid-execution causing silent cancellation
Similar / contraste
asyncio.ensure_future() (older, more generic), loop.call_soon_threadsafe() (scheduling callbacks), asyncio.create_task() (preferred shortcut)
Interferências
Coming from threading: may think create_task spawns an OS thread; actually it schedules on the same event loop thread.
Família do chunk
- asyncio.create_task
- ensure_future
- gather
- wait
- sleep
Nuance
Tasks are scheduled to run on the loop; if the loop is not running, they won't execute until run_until_complete or run_forever; tasks can be cancelled; exceptions propagate when awaited.
Efeito pragmático
Enables concurrent execution of async operations, simplifies managing multiple coroutines.
Dica de memória
Fire‑and‑forget async work with loop.create_task()
Nota
In Python 3.7+, asyncio.create_task() is the preferred shortcut; loop.create_task() requires a running event loop obtained via asyncio.get_running_loop().
Upgrade path
Use asyncio.create_task() for brevity, or manage task lifecycle with asyncio.gather() or task groups (Python 3.11+).
Log in to save chunks.