CKTIS / Python
Leggere il nome di un task con `asyncio.Task.get_name()`
`get_name()` restituisce il nome corrente di un task asyncio come stringa. Usalo come etichetta in un resoconto e verifica separatamente con `cancelled()` se il task è stato davvero annullato.
Versione: Python 3.12
Sintassi
task.get_name() # returns strtask.get_name() è un metodo di istanza sincrono di asyncio.Task, disponibile da Python 3.8. Non accetta argomenti e restituisce il nome corrente come str. Non serve await: puoi leggere il nome sia prima sia dopo che il task termina.
Assegna un nome con asyncio.create_task(coro, name=...) oppure cambialo con task.set_name(value), che converte il valore in una stringa. Se non assegni un nome esplicito, l’implementazione standard di Task ne genera uno alla creazione. Usalo come etichetta diagnostica, non come identificatore univoco o indicatore di stato.
task.cancel() richiede l’annullamento, ma non lo garantisce: la coroutine può intercettare e sopprimere asyncio.CancelledError. Per riportare l’esito, attendi la fine con await task, gestisci l’eccezione asyncio.CancelledError attesa e controlla task.cancelled(). Di norma, la coroutine dovrebbe liberare le risorse in finally e lasciare che l’annullamento si propaghi.
Esempi
import asyncio
async def worker(started):
started.set()
await asyncio.Event().wait()
async def main():
started = asyncio.Event()
task = asyncio.create_task(worker(started), name="report-worker")
await started.wait()
task.cancel()
try:
await task
except asyncio.CancelledError:
print(f"{task.get_name()}: cancelled={task.cancelled()}")
if __name__ == "__main__":
asyncio.run(main())Risultato
report-worker: cancelled=True
L’evento `started` permette al chiamante di attendere l’avvio della coroutine senza un ritardo prefissato. Il secondo evento non viene mai impostato, quindi il task resta in attesa fino all’annullamento. Il resoconto abbina il nome esplicito allo stato confermato dopo `await task`.
Lezioni correlate
- Python · Lezione 30 · Avanzato · Versione: 5
Fonti
- Coroutines and Tasks — Task.get_name() (Python 3.12)
- Coroutines and Tasks — asyncio.create_task() (Python 3.12)
- Coroutines and Tasks — Task.set_name() (Python 3.12)
- Coroutines and Tasks — Task.cancel() (Python 3.12)
- Coroutines and Tasks — Task.cancelled() (Python 3.12)
- Coroutines and Tasks — Task Cancellation (Python 3.12)