Type Hints
Add static type annotations with type hints, the typing module, and mypy for type checking.
What you'll learn
- Annotate functions with type hints
- Use the typing module for complex types
- Understand Optional, Union, and generics
- Run mypy for static type checking
- Balance type hints with Python's dynamic nature
Concept
Basic Type Hints
Type hints (PEP 484) let you annotate the expected types of variables, parameters, and return values. They are optional and do not change runtime behavior — they are for static analysis tools like mypy:
def greet(name: str) -> str:
return f"Hello, {name}!"
def add(a: int, b: int) -> int:
return a + b
age: int = 25
name: str = "Ada"
The syntax is parameter: type for parameters and -> type for return values. Python ignores these at runtime — they are metadata stored in __annotations__. Tools like mypy, pyright, and IDEs use them to catch type errors before you run the code.
Why Type Hints?
- Catch bugs early — mypy finds type errors before runtime
- Better IDE support — autocomplete, inline documentation, refactoring
- Self-documenting — the signature shows what types are expected
- Easier refactoring — the type checker verifies changes across the codebase
# Install and run mypy
pip install mypy
mypy my_script.py
Variables and Collections
# Variable annotations
count: int = 0
price: float = 19.99
name: str = "Ada"
is_active: bool = True
# Collection types (Python 3.9+ — use built-in types directly)
numbers: list[int] = [1, 2, 3]
names: list[str] = ["Ada", "Bob"]
scores: dict[str, int] = {"math": 90, "science": 85}
point: tuple[int, int] = (10, 20)
unique: set[str] = {"a", "b", "c"}
In Python 3.9+, you can use list[int] directly. In 3.8 and earlier, you need from typing import List and use List[int].
The typing Module
For more complex types, use the typing module:
from typing import Optional, Union, Any, Callable, Iterable
# Optional — either the type or None
def find_user(user_id: int) -> Optional[dict]:
# Returns a dict or None if not found
...
# Union — one of several types
def process(data: Union[str, bytes]) -> str:
...
# Any — any type (disables checking)
def debug(value: Any) -> None:
print(value)
# Callable — a function type
def apply(func: Callable[[int, int], int], a: int, b: int) -> int:
return func(a, b)
In Python 3.10+, you can use X | Y instead of Union[X, Y] and X | None instead of Optional[X]:
def find_user(user_id: int) -> dict | None:
...
def process(data: str | bytes) -> str:
...
Type Hints for Functions
from typing import List, Dict, Tuple
def process_items(items: List[str]) -> Dict[str, int]:
"""Count occurrences of each string."""
result: Dict[str, int] = {}
for item in items:
result[item] = result.get(item, 0) + 1
return result
def split_point(p: Tuple[int, int]) -> Tuple[int, int]:
return p[0], p[1]
Generic Types with TypeVar
from typing import TypeVar, List
T = TypeVar("T") # T can be any type
def first(items: List[T]) -> T:
"""Return the first element of a list, preserving the type."""
return items[0]
# mypy knows first([1, 2, 3]) returns int
# and first(["a", "b"]) returns str
TypeVar lets you express relationships between types — "the return type matches the list element type." This is called generics and is powerful for reusable, type-safe functions.
TypedDict — Typed Dictionaries
from typing import TypedDict
class UserDict(TypedDict):
name: str
age: int
email: str
user: UserDict = {"name": "Ada", "age": 25, "email": "ada@x.com"}
# mypy checks that all required keys are present with the right types
TypedDict lets you type dictionaries with fixed keys — useful for JSON data and API responses.
Type Aliases
# Create a named alias for a complex type
UserID = int
UserMap = dict[UserID, str]
def get_name(users: UserMap, uid: UserID) -> str:
return users[uid]
Running mypy
# Check a file
mypy script.py
# Check a package
mypy -p mypackage
# Strict mode
mypy --strict script.py
# Common errors:
# error: Argument 1 to "add" has incompatible type "str"; expected "int"
mypy catches type mismatches that would cause TypeError at runtime. Start with gradual typing — add hints to new code and critical functions first, then expand over time.
When to Use Type Hints
- Public APIs — library functions, class interfaces
- Complex functions — where the expected types are not obvious
- Team projects — where others benefit from the documentation
- New code — add hints as you write, not retroactively
Type hints are optional — you do not need them everywhere. Start with function signatures and expand as needed. Python remains dynamically typed; hints are a development aid, not a runtime enforcement.
Example
from typing import Optional, Union, Any, Callable, TypeVar, List, Dict
# Basic type hints
def greet(name: str, times: int = 1) -> str:
"""Greet someone, repeated."""
return (f"Hello, {name}! " * times).strip()
print(greet("Ada", 3))
# Optional and Union
def find_user(user_id: int) -> Optional[dict]:
users = {1: {"name": "Ada"}, 2: {"name": "Bob"}}
return users.get(user_id) # returns dict or None
result = find_user(1)
print(f"Found: {result}")
print(f"Not found: {find_user(99)}")
# Collection types
def count_words(words: List[str]) -> Dict[str, int]:
counts: Dict[str, int] = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
return counts
print(count_words(["apple", "banana", "apple", "cherry", "banana", "apple"]))
# TypeVar — generics
T = TypeVar("T")
def first(items: List[T]) -> T:
return items[0]
print(first([1, 2, 3])) # mypy knows this returns int
print(first(["a", "b"])) # mypy knows this returns str
# Callable type
def apply_twice(func: Callable[[int], int], value: int) -> int:
return func(func(value))
print(apply_twice(lambda x: x + 3, 10)) # 16
# TypedDict for structured dicts
from typing import TypedDict
class User(TypedDict):
name: str
age: int
active: bool
user: User = {"name": "Ada", "age": 25, "active": True}
print(f"{user['name']}, age {user['age']}, active: {user['active']}")
# Variable annotations
count: int = 42
pi: float = 3.14159
tags: List[str] = ["python", "code"]
# Type alias
UserID = int
UserMap = Dict[UserID, str]
users: UserMap = {1: "Ada", 2: "Bob"}
print(f"User 1: {users[1]}")
Shows basic function annotations, Optional/Union, collection types (List, Dict), TypeVar generics, Callable for function parameters, TypedDict for structured dicts, variable annotations, and type aliases.
Try it
- JSON Formatter
TypedDict and type hints are useful for typing JSON data structures.
- Case Converter
Type hints document the input/output types of conversion functions.
Common mistakes
The mistake
Using List/Dict from typing in Python 3.9+ instead of the built-in list/dict
The fix
In Python 3.9+, use list[int] and dict[str, int] directly instead of typing.List and typing.Dict. The typing versions are deprecated. For Python 3.8 and earlier, you must use the typing module versions.
The mistake
Expecting type hints to be enforced at runtime
The fix
Type hints are not checked at runtime — Python remains dynamically typed. They are metadata for static analysis tools like mypy. If you need runtime type checking, use a library like pydantic or typeguard. Run mypy separately to catch type errors.
Related Resources
Related Cheatsheets
- Python Cheatsheet
Type hint syntax, typing module, and mypy usage.
Practice Type Hints
2 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.