Type hints annotate expected types for static checkers (mypy, pyright)—Python still enforces types at runtime dynamically. Compare with compile-time guarantees in Java or C#.
Function and variable annotations
def greet(name: str) -> str:
return f"Hi, {name}!"
count: int = 0
items: list[str] = []
Optional and union syntax
def find_user(user_id: int) -> dict | None:
return None
Python 3.10+ uses X | Y; older code uses Optional[X] from typing.
Important interview questions and answers
- Q: Do hints affect runtime?
A: No by default—they are stored in__annotations__for tools; use pydantic or validators for runtime checks. - Q: Why use hints in dynamic Python?
A: IDE support, documentation, and catching bugs in CI with mypy—especially in large codebases.
Self-check
- What tool checks hints statically?
- Does Python reject str + int at runtime without hints?
Tip: Run mypy in CI—hints document intent but CPython ignores them at runtime by default.
Interview prep
- Runtime enforcement?
No by default—use mypy/pyright in CI; pydantic for runtime validation if needed.
- Why hints in dynamic Python?
Documentation, IDE autocomplete, and catching bugs before runtime in large teams.