AdvancedLesson 12 of 12
Type Hints & asyncio – Python
Static type checking and concurrent I/O.
Type hints document types and let tools like mypy find errors – Python itself does not enforce them.
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)With asyncio, many I/O tasks (network, files) run concurrently in a single thread:
import asyncio
async def hole(name, sek):
await asyncio.sleep(sek)
return f"{name} done after {sek}s"
async def main():
ergebnisse = await asyncio.gather(hole("A", 1), hole("B", 2), hole("C", 1))
print(ergebnisse) # takes ~2s instead of 4s
asyncio.run(main())Tipasyncio helps with I/O-bound tasks. For compute-intensive tasks use
multiprocessing or concurrent.futures.ProcessPoolExecutor.