Python type hints mạnh mẽ hơn chỉ int, str cơ bản:
python
from typing import Optional, Union, TypeVar, Generic, Protocol
from collections.abc import Sequence
# Optional[X] tương đương Union[X, None]
def find_user(user_id: int) -> Optional[User]:
return db.get(user_id) # Có thể None
# Union — nhiều types
def parse_id(value: Union[str, int]) -> int:
return int(value)
# TypeVar — generic type variable
T = TypeVar('T')
def first(lst: Sequence[T]) -> Optional[T]:
return lst[0] if lst else None
# Generic class
class Stack(Generic[T]):
def __init__(self): self._items: list[T] = []
def push(self, item: T) -> None: self._items.append(item)
def pop(self) -> T: return self._items.pop()
# Protocol — structural subtyping (duck typing + type safety)
class Drawable(Protocol):
def draw(self) -> None: ...
def render(obj: Drawable) -> None:
obj.draw() # Bất kỳ class nào có .draw() đều hợp lệPython 3.10+: dùng X | Y thay vì Union[X, Y], X | None thay vì Optional[X].