Asincrono/Aspetta in Python
La programmazione asincrona consente l'esecuzione simultanea senza thread, ideale per attività legate a I/O.
Concetti fondamentali
import asyncio
async def fetch_data() -> str:
await asyncio.sleep(1) # Simulates I/O
return "data"
async def main():
result = await fetch_data()
print(result)
asyncio.run(main())
Esecuzione di attività contemporaneamente
async def main():
# Sequential - takes 3 seconds
a = await fetch_data()
b = await fetch_data()
c = await fetch_data()
# Concurrent - takes 1 second
a, b, c = await asyncio.gather(
fetch_data(),
fetch_data(),
fetch_data()
)
Esempio reale: richieste HTTP
CODICE_BLOCCO_2
Quando utilizzare Async
Buono per: - Richieste HTTP - Interrogazioni del database - I/O file - WebSocket
Non ideale per:
- Attività legate alla CPU (usa multiprocessing)
- Script semplici con I/O minimi