Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / Python

asyncio.Task

Rappresenta una coroutine eseguita cooperativamente dal ciclo.

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

Sintassi

task = asyncio.create_task(coro)

Rappresenta una coroutine eseguita cooperativamente dal ciclo.

name identifica il task, context sceglie il contesto ed eager_start permette l’avvio immediato. Il risultato proviene dalla coroutine. Le operazioni esterne set_result e set_exception di Future non sono ammesse. Quando si sospende su await altri task possono avanzare. Attendere il task restituisce il valore o propaga l’eccezione. result() prima del completamento solleva InvalidStateError e cancel() richiede l’annullamento.

Il segnale permette al task di restituire True.

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() restituisce il nome del task, qui reader. cancel(msg) richiede di iniettare CancelledError al prossimo giro del ciclo. La coroutine può intercettarlo. A task terminato, cancel() restituisce 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())

Esempi

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())

Risultato

True
InvalidStateError
True

Il segnale permette al task di restituire True.

Fonti