CKTIS / Python
Lire le nom d’une tâche avec `asyncio.Task.get_name()`
`get_name()` renvoie le nom actuel d’une tâche asyncio sous forme de chaîne. Utilisez-le comme libellé dans un rapport, puis vérifiez séparément avec `cancelled()` si la tâche a bien été annulée.
Version : Python 3.12
Syntaxe
task.get_name() # returns strtask.get_name() est une méthode d’instance synchrone de asyncio.Task, disponible depuis Python 3.8. Elle ne prend aucun argument et renvoie le nom actuel sous forme de str. Aucun await n’est nécessaire : le nom reste lisible avant comme après la fin de la tâche.
Attribuez un nom avec asyncio.create_task(coro, name=...) ou modifiez-le avec task.set_name(value), qui convertit la valeur en chaîne. Sans nom explicite, l’implémentation standard de Task en génère un à la création. Ce nom sert de libellé de diagnostic, pas d’identifiant unique ni d’indicateur d’état.
task.cancel() demande l’annulation sans la garantir : la coroutine peut intercepter et supprimer asyncio.CancelledError. Pour rendre compte du résultat, attendez la fin avec await task, traitez l’exception asyncio.CancelledError attendue et consultez task.cancelled(). En règle générale, la coroutine doit libérer ses ressources dans finally et laisser l’annulation se propager.
Exemples
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())Résultat
report-worker: cancelled=True
L’événement `started` permet à l’appelant d’attendre le démarrage de la coroutine sans délai prédéfini. Le second événement n’est jamais signalé, donc la tâche reste en attente jusqu’à son annulation. Le rapport associe le nom explicite à l’état confirmé après `await task`.
Leçons associées
- Python · Leçon 30 · Avancé · Version : 5
Sources
- 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)