Python - callback

Voir :

Notes Python multithreading

Introduction

Exemple d'une fonction sans callback

#! /usr/bin/env python3 from functools import reduce def calcfact(i): assert i >= 0 return reduce(lambda a, b: a * b, range(1, i+1) if i > 1 else [1]) print(calcfact(3))

Exemple de la même fonction avec callback optionnel

#! /usr/bin/env python3 from functools import reduce def calcfact_called(i, res): print(i, '! = ', res, sep='') def calcfact(i, callback=None): assert i >= 0 res = reduce(lambda a, b: a * b, range(1, i+1) if i > 1 else [1]) if callback is None: return res else: callback(i, res) # Sans Callback print(calcfact(3)) # Avec Callback calcfact(4, calcfact_called)

Exemple avec async / asyncio / await

#! /usr/bin/env python3 import asyncio def waitplop_called(i): print(i) async def waitplop(i, callback=None): await asyncio.sleep(i) if callback is None: return i else: callback(i) async def main(): async with asyncio.TaskGroup() as tg: # Asynchronous with callback tg.create_task(waitplop(3, waitplop_called)) tg.create_task(waitplop(3, waitplop_called)) # Synchronous / sequential without callback task1 = await tg.create_task(waitplop(4)) print(task1) asyncio.run(main())

$ time ./plop.py
3
3
4
real 0m4.120s
user 0m0.095s
sys 0m0.024s

Autre façon de faire un callback avec asyncio

Voir :

https://www.youtube.com/watch?v=gn6qo3k97hM

#! /usr/bin/env python3 import asyncio def waitplop_called(task): print(task.result()) async def waitplop(i): await asyncio.sleep(i) return i async def main(): task = asyncio.create_task(waitplop(3)) task.add_done_callback(waitplop_called) await asyncio.gather(task) asyncio.run(main())

Autres

Voir :

https://docs.python.org/fr/3/library/asyncio-future.html

# Call 'print("Future:", fut)' when "fut" is done. fut.add_done_callback( functools.partial(print, "Future:"))