Capitolo 17: Type Hints & Typing Statico

Aggiungi annotazioni di tipo a funzioni, variabili e classi e sfrutta il modulo typing per codice più sicuro e auto-documentato.

Scarica chapter17.py

Obiettivi

1. Annotazioni di Funzione

def greet(name: str) -> str:
    return f"Hello, {name}"

def add(a: int, b: int) -> int:
    return a + b

print(greet.__annotations__)
# {'name': , 'return': }

2. Annotazioni per Variabili

from typing import List

ages: List[int] = [25, 30, 35]
threshold: float = 4.5

print(globals().get('__annotations__'))
# {'ages': list[int], 'threshold': float}

3. Tipi Comuni da typing

from typing import Optional, Union, Any, Dict

def find_user(user_id: int) -> Optional[Dict[str, Any]]:
    users = {1: {"name": "Alice"}}
    return users.get(user_id)

def process(data: Union[str, bytes]) -> None:
    print(data)

user = find_user(2)
if user is None:
    print("Non trovato")

4. Generici & TypeVar

from typing import TypeVar, Generic, List

T = TypeVar('T')

class Stack(Generic[T]):
    def __init__(self) -> None:
        self._items: List[T] = []

    def push(self, item: T) -> None:
        self._items.append(item)

    def pop(self) -> T:
        return self._items.pop()

int_stack = Stack[int]()
int_stack.push(1)
str_stack = Stack[str]()
str_stack.push("hello")

5. Controllo Statico con mypy

pip install mypy
mypy src/chapter17.py --strict

Correggi gli errori segnalati per allineare annotazioni e utilizzo.

Esercizi

  1. Aggiungi type hints a un modulo calcolatrice (add, sub, mul, div).
  2. Annota una funzione di caricamento dati che ritorna List[Dict[str, Any]].
  3. Crea una classe generica Queue[T] con metodi enqueue() e dequeue().
  4. Esegui mypy sul codice e risolvi tutti gli errori di tipo.