Mis a jour le 2025-04-14, 12:10

asyncio

coroutine :
  • c'est une version spécialisée d'une fonction ou d'un generator qui peut suspendre son exécution avant d'atteindre le return ou le yield.
  • on la déclare avec async def myFunc1(...)
  • elle peut contenir un await myFunc2(...) : ça va suspendre temporairement l'exécution de myFunc1 et faire autre chose jusqu'à ce que le résultat de myFunc2 soit disponible.
  • une fonction déclarée avec async peut utiliser await, return et/ou yield.
  • await ne peut être utilisé qu'à l'intérieur d'une fonction async.
  • pour appeler une fonction async, il faut l'appeler avec await myFunc1(...)
  • await ne peut être appliqué qu'à un un objet awaitable : soit une fonction async, soit un objet qui définit une méthode __await__() qui retourne un itérateur.
Fonctions disponibles :
  • asyncio.sleep(2) : coroutine qui ne fait rien (ici pendant 2 secondes).
  • asyncio.run(f()) : prend le contrôle de l'event loop et exécute la coroutine f.
  • asyncio.gather(f1(), f2(), f3()) : coroutine qui appelle les coroutines f1, f2 et f3, et retourne la liste des résultats une fois que tous les appels sont terminés.
  • asyncio.create_task(f1()) : programme l'exécution d'une coroutine f1
Exemple avec gather :
import asyncio
async def f1():
    print('start f1')
    await asyncio.sleep(1)
    print('end f1')
    return 2

async def f2():
    print('start f2')
    await asyncio.sleep(5)
    print('end f2')
    return 10
    
async def f3():
    print('start f3')
    await asyncio.sleep(2)
    print('end f3')
    return 4
    
async def g():
    result = await asyncio.gather(f1(), f2(), f3())
    return result

result = asyncio.run(g())
print(result)
  
donne
start f1
start f2
start f3
end f1
end f3
end f2
[2, 10, 4]
  
Exemple avec create_task :
import asyncio

async def f1():
    print('start f1')
    await asyncio.sleep(1)
    print('end f1')

async def f2():
    print('start f2')
    await asyncio.sleep(5)
    print('end f2')
    
async def f3():
    print('start f3')
    await asyncio.sleep(2)
    print('end f3')
    
async def g():
    t1 = asyncio.create_task(f1())
    t2 = asyncio.create_task(f2())
    t3 = asyncio.create_task(f3())

    await asyncio.wait([t1, t2, t3])

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
asyncio.run(g())
  

Copyright python-simple.com
programmer en python, tutoriel python, graphes en python, Aymeric Duclert