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.
Scaricachapter17.py
Obiettivi
- Annotare parametri e tipi di ritorno delle funzioni.
- Usare annotazioni per variabili.
- Importare e usare tipi comuni da
typing
(List, Dict, Optional, Union, Any). - Definire generici con
TypeVar
eGeneric
. - Eseguire controlli statici con
mypy
.
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
- Aggiungi type hints a un modulo calcolatrice (add, sub, mul, div).
- Annota una funzione di caricamento dati che ritorna
List[Dict[str, Any]]
. - Crea una classe generica
Queue[T]
con metodienqueue()
edequeue()
. - Esegui
mypy
sul codice e risolvi tutti gli errori di tipo.