Outils pour utilisateurs

Outils du site


tech:python_-_callback

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

tech:python_-_callback [2025/03/24 15:06] – créée - modification externe 127.0.0.1tech:python_-_callback [2026/05/30 21:31] (Version actuelle) Jean-Baptiste
Ligne 1: Ligne 1:
 +<!DOCTYPE markdown>
 +{{tag>Brouillon Python CA}}
 +
 +# Python - callback
 +
 +Voir :
 +* [[Notes Python multithreading]]
 +
 +## Introduction
 +
 +Exemple d'une fonction sans callback
 +~~~python
 +#! /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
 +~~~python
 +#! /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
 +
 +~~~python
 +#! /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
 +
 +~~~python
 +#! /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
 +
 +~~~python
 +# Call 'print("Future:", fut)' when "fut" is done.
 +fut.add_done_callback(
 +    functools.partial(print, "Future:"))
 +~~~
 +
  

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki