Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

asyncio.Task

Wraps a coroutine in a scheduled awaitable with result, status and cancellation controls.

Version: Python 3.14; repository image, production runtime not attested

Syntax

task = asyncio.create_task(coro)

Wraps a coroutine in a scheduled awaitable with result, status and cancellation controls.

Reading the result before completion raises InvalidStateError. Awaiting the task synchronizes with completion.

A Task drives a coroutine cooperatively on one event loop. Other tasks can run when it suspends on an awaitable. Awaiting the task returns its value or propagates its failure. result() on a pending task raises InvalidStateError. cancel() requests interruption rather than immediately marking it cancelled. The gate keeps the sample pending until it returns True. name identifies the task, context selects its context and eager_start permits immediate execution. The wrapped coroutine owns its result. External set_result and set_exception calls are rejected.

import asyncio
async def main():
    async def fail():
        raise LookupError("missing")
    t = asyncio.create_task(fail())
    try:
        await t
    except LookupError:
        assert t.done() and isinstance(t.exception(), LookupError)
    else:
        raise AssertionError
asyncio.run(main())
import asyncio
async def main():
    t = asyncio.create_task(asyncio.sleep(0, result=3), name="job")
    for mutate in (lambda: t.set_result(4), lambda: t.set_exception(ValueError())):
        try:
            mutate()
        except RuntimeError:
            pass
        else:
            raise AssertionError
    assert await t == 3 and t.get_name() == "job"
asyncio.run(main())

asyncio.Task.cancel · asyncio.Task.get_name

get_name() returns the task name, here reader. cancel(msg) requests injection of CancelledError on the next event-loop cycle. The coroutine can catch it. Once the task is done, cancel() returns False.

import asyncio
async def main():
    ready = asyncio.Event()
    async def idle():
        ready.set()
        await asyncio.Event().wait()
    task = asyncio.create_task(idle(), name="reader")
    await ready.wait()
    assert task.get_name() == "reader" and task.cancel("done")
    try:
        await task
    except asyncio.CancelledError as exc:
        assert exc.args == ("done",)
    assert task.cancelled() and not task.cancel()
asyncio.run(main())

Examples

import asyncio

async def main():
    gate = asyncio.Event()
    task = asyncio.create_task(gate.wait())
    print(isinstance(task, asyncio.Task))
    try:
        task.result()
    except asyncio.InvalidStateError as error:
        print(type(error).__name__)
    gate.set()
    print(await task)

asyncio.run(main())

Result

True
InvalidStateError
True

A Task drives a coroutine cooperatively on one event loop. Other tasks can run when it suspends on an awaitable. Awaiting the task returns its value or propagates its failure. result() on a pending task raises InvalidStateError. cancel() requests interruption rather than immediately marking it cancelled. The gate keeps the sample pending until it returns True. name identifies the task, context selects its context and eager_start permits immediate execution. The wrapped coroutine owns its result. External set_result and set_exception calls are rejected.

Sources