Python Type Hints — Static Typing for Python
Type hints document expected types and enable static analysis. They catch bugs before runtime and improve code readability.
Learning Objectives
- Add type hints to functions and variables
- Use advanced types (Union, Optional, TypeVar)
- Define protocols and typed structures
- Run mypy for static type checking
Basic Type Hints
def greet(name: str) -> str:
return f"Hello, {name}"
def add(a: int, b: int) -> int:
return a + b
# Variables
age: int = 25
name: str = "Alice"
scores: list[int] = [95, 87, 91]
Advanced Types
from typing import Union, Optional, TypeVar, Generic
# Union — multiple types
def process(value: Union[int, str]) -> str:
return str(value)
# Optional — value or None
def find(name: str) -> Optional[dict]:
return None
# TypeVar — generic types
T = TypeVar('T')
def first(items: list[T]) -> T:
return items[0]
# TypedDict
from typing import TypedDict
class UserDict(TypedDict):
name: str
age: int
email: str
# Callable
from typing import Callable
def apply(func: Callable[[int, int], int], a: int, b: int) -> int:
return func(a, b)
Protocol (Structural Subtyping)
from typing import Protocol
class Drawable(Protocol):
def draw(self) -> str: ...
class Circle:
def draw(self) -> str:
return "O"
class Square:
def draw(self) -> str:
return "[]"
def render(shape: Drawable) -> str:
return shape.draw()
render(Circle()) # "O"
render(Square()) # "[]"
Mypy Static Checking
# Install: pip install mypy
# Run: mypy your_script.py
def add(a: int, b: int) -> int:
return a + b
add("hello", "world") # mypy error: Argument 1 has type "str"
Key Takeaways
- Add type hints for better IDE support and documentation
- Use
Optional[X]instead ofUnion[X, None] - Use
TypeVarfor generic functions and classes - Use
Protocolfor structural subtyping - Run
mypyto catch type errors statically