Introduction
Python is dynamically typed — and that’s great for prototyping. But as projects grow, “what does this function return?” becomes a guessing game. Type hints + mypy give you static checking without changing Python’s runtime behavior. Zero performance cost, massive safety gain.
This post is the practical guide: enough type hints to be useful, without the academic rabbit hole.
The basics
def greet(name: str, times: int = 1) -> str:
return (f"Hello, {name}!\n" * times).strip()
greet("Galvan", 2) # OK
greet(42) # mypy error: int not str
Hints are ignored at runtime — Python doesn’t enforce them. They’re documentation that tools can check.
Common types
from typing import Optional, List, Dict, Tuple, Set, Union
def process(items: List[str]) -> Dict[str, int]:
return {item: len(item) for item in items}
def find(name: str) -> Optional[str]: # might return None
...
def parse(value: str) -> Union[int, float]:
...
In Python 3.9+, use built-ins directly: list[str], dict[str, int], tuple[int, ...]. Cleaner.
Optional and None checks
def get_user(user_id: int) -> Optional[dict]:
...
user = get_user(1)
if user is not None: # mypy now knows user is dict here
print(user["name"])
mypy uses narrowing — after an is not None check, it treats the variable as non-None.
Generics
from typing import TypeVar, Generic
T = TypeVar("T")
class Box(Generic[T]):
def __init__(self, value: T):
self.value = value
def get(self) -> T:
return self.value
b: Box[int] = Box(42)
x: int = b.get() # mypy knows this is int
For most code, use list[T], dict[K, V] instead of defining your own generics.
TypedDict for dict shapes
from typing import TypedDict
class User(TypedDict):
id: int
name: str
email: str
def create_user(u: User) -> None:
...
create_user({"id": 1, "name": "Galvan", "email": "[email protected]"}) # OK
create_user({"id": 1, "name": "Galvan"}) # mypy error: missing 'email'
Great for JSON payloads, API responses, and config dicts.
Protocol for duck typing
from typing import Protocol
class Drawable(Protocol):
def draw(self) -> None: ...
def render(obj: Drawable) -> None:
obj.draw()
class Circle:
def draw(self) -> None:
print("○")
render(Circle()) # OK — Circle has draw(), no inheritance needed
Protocols let you type “anything with a draw method” without forcing inheritance.
Literal for fixed values
from typing import Literal
def set_level(level: Literal["debug", "info", "warning", "error"]) -> None:
...
set_level("debug") # OK
set_level("verbose") # mypy error
Great for config options, modes, and status strings.
Running mypy
pip install mypy
mypy your_package/
Config in pyproject.toml:
[tool.mypy]
python_version = "3.11"
strict = true
warn_return_any = true
warn_unused_configs = true
ignore_missing_imports = true
Start with strict = false and tighten over time. Don’t enable everything on day one — you’ll drown in errors.
Practical workflow
- Add hints to new code (functions you write today).
- Run mypy in CI — fail the build on errors.
- Gradually annotate legacy code — file by file, not all at once.
- Use
# type: ignoresparingly — only for third-party libs without stubs. - IDE integration — VS Code + Pylance gives inline errors as you type.
Type hints + FastAPI/Pydantic
FastAPI uses type hints for validation and docs — they’re not just for mypy:
from fastapi import FastAPI
from pydantic import BaseModel
class UserIn(BaseModel):
name: str
age: int
app = FastAPI()
@app.post("/users")
def create(user: UserIn) -> UserIn:
return user # validated, documented, typed
Same hints, three jobs: runtime validation (Pydantic), API docs (OpenAPI), static checking (mypy).
Common mistakes
- Over-typing —
def add(a: int, b: int) -> intis fine;def add(a: int) -> Callable[[int], int]for a simple function is overkill. Anyeverywhere —Anydisables checking. Use it only at boundaries (JSON parsing, third-party libs).- Ignoring
None—def find() -> strwhen it can returnNoneis a bug waiting to happen. UseOptional[str]. - No CI enforcement — hints without CI are just comments. Run mypy in CI.
- Strict mode on day one — start loose, tighten gradually.
Key Concepts
- Type hints = annotations ignored at runtime, checked by tools
- mypy = static type checker for Python
Optional= value or NoneTypedDict= typed dict shapesProtocol= structural (duck) typingLiteral= fixed allowed values
What to Try Next
- Add type hints to your FastAPI backend — FastAPI uses them for validation.
- Type your Streamlit app — catch bugs before runtime.
- Use
TypedDictfor your RAG chunk metadata. - Enable mypy in CI for one module and expand.
FAQ
Do type hints slow down Python?
No — they’re ignored at runtime. Zero performance cost. mypy runs at dev/CI time, not runtime.
Type hints vs Pydantic — same thing?
Related but different. Type hints are static (mypy). Pydantic uses type hints for runtime validation. FastAPI combines both. You can use type hints without Pydantic, and Pydantic without mypy.
Should I type everything?
Type public APIs and function signatures. Internal helpers can stay untyped until they cause bugs. Pragmatism over purity.