Type hints catch bugs before runtime, improve IDE autocomplete, and serve as documentation.
Basic Types¶
from typing import Optional def greet(name: str, times: int = 1) -> str: return f”Hello {name}! ” * times def find_user(user_id: int) -> Optional[dict]: … # May return None
Python Typing — Type Annotations¶
def process(data: str | None) -> list[int]: …
Generics and Protocol¶
from typing import TypeVar, Protocol T = TypeVar(‘T’) def first(items: list[T]) -> T: return items[0] class Renderable(Protocol): def render(self) -> str: … def display(item: Renderable) -> None: print(item.render())
mypy¶
pyproject.toml¶
[tool.mypy] strict = true warn_return_any = true
Run¶
mypy src/
Key Takeaway¶
Type hints everywhere + mypy –strict. Catches bugs before runtime, improves DX.