Lesson 53 of 55 · Python
Type Hinting & Static Typing
Duration: 20 minutes
Type Hinting & Static Typing
Python’s dynamic nature makes it easy to write quick scripts, but large code‑bases benefit from type annotations – they improve readability, help IDEs, and enable static analysis tools like mypy.
1️⃣ Basic Syntax (PEP 484)
def greet(name: str) -> str:
return f"Hello, {name}!"
age: int = 27
items: list[int] = [1, 2, 3]
- The part after
:is the type hint for a variable. - The part after
->is the return type.
2️⃣ The typing Module
from typing import List, Tuple, Dict, Optional, Union, Any, Callable
def process(data: List[int]) -> Tuple[int, float]:
total = sum(data)
avg = total / len(data) if data else 0.0
return total, avg
Frequently used types
| Hint | Meaning |
|---|---|
List[int] | List containing only integers |
Dict[str, Any] | Mapping from strings to any value |
Optional[str] | str or None |
Union[int, float] | Either int or float |
Callable[[int, int], int] | Function taking two ints and returning an int |
3️⃣ Runtime vs. Static Checking
- Runtime: Python ignores hints – they are just metadata.
- Static: Tools like
mypy,pyrightor IDEs read hints and warn about mismatches.
# Install mypy
pip install mypy
# Run a type‑check on a file
mypy myscript.py
Typical output:
myscript.py:5: error: Incompatible types in assignment (expression has type "int", variable has type "str")
4️⃣ Gradual Adoption
- Add hints to public APIs first (functions, classes).
- Run
mypy --strictlocally; fix the most critical errors. - Keep the code working – you can always add more hints later.
5️⃣ Advanced Topics (quick glance)
- TypedDict – typed dictionaries for JSON‑like data.
- Protocol – structural subtyping (duck‑typing with static checks).
- New‑type – create distinct types from existing ones (e.g.,
UserId = NewType('UserId', int)). - Annotated – attach extra metadata (e.g., for validation libraries).
When you combine type hints with good test coverage, your Python projects become far easier to maintain and refactor.