ProfiLektion 12 von 12
Typhinweise & asyncio – Python
Statische Typprüfung und nebenläufige I/O.
Typhinweise (Type Hints) dokumentieren Typen und lassen Tools wie mypy Fehler finden – Python selbst erzwingt sie nicht.
from typing import Optional
def teile(a: float, b: float) -> Optional[float]:
return None if b == 0 else a / b
namen: list[str] = ["Ada", "Linus"]
print(teile(1, 0), teile(6, 3), namen)Mit asyncio laufen viele I/O-Aufgaben (Netzwerk, Dateien) gleichzeitig in einem Thread:
import asyncio
async def hole(name, sek):
await asyncio.sleep(sek)
return f"{name} fertig nach {sek}s"
async def main():
ergebnisse = await asyncio.gather(hole("A", 1), hole("B", 2), hole("C", 1))
print(ergebnisse) # dauert ~2s statt 4s
asyncio.run(main())Tippasyncio hilft bei I/O-bound Aufgaben. Für rechenintensive Aufgaben nimm
multiprocessing oder concurrent.futures.ProcessPoolExecutor.