🐍 Python Advanced

What is Python's type system and static typing with mypy?

Answer

Python is dynamically typed at runtime (types are checked when code executes), but supports gradual static typing through type annotations and external type checkers. mypy is the most popular static type checker — it checks type annotations without running the code. pyright (Microsoft) is faster and used by Pylance in VS Code. Generic types: list[int], dict[str, Any], tuple[int, str, float]. TypeVar for generics: T = TypeVar("T"); def first(lst: list[T]) -> T: return lst[0]. Protocol (structural subtyping): class Drawable(Protocol): def draw(self) -> None — any class with a draw() method satisfies it, without explicit inheritance. TypedDict: type-checked dicts. Literal: specific literal types. Final: constants. Overload: multiple signatures. Runtime type checking: Pydantic validates types at runtime using annotations.