Add optional type hints to catch bugs early, document your code, and check everything with mypy before you run it.
Why: Python does not require you to declare types, but adding them documents what a function expects and returns. Your editor uses them for better autocomplete and warnings, and tools can catch mismatches before the code ever runs. They do not change how the program executes.
def greet(name: str) -> str:
return f'Hello, {name}'
age: int = 30
price: float = 19.99
is_active: bool = TrueWhy: you can describe what is inside a list or dict too. Since Python 3.9 you use the built-in types directly — list[int] means "a list of ints".
def total(prices: list[float]) -> float:
return sum(prices)
scores: dict[str, int] = {'ada': 90, 'bob': 80}
names: list[str] = ['Ada', 'Bob']Why: when a value might be missing, say so. "str | None" means "a string or None". This pushes you to handle the missing case and prevents a whole class of bugs.
def find_user(user_id: int) -> str | None:
users = {1: 'Ada'}
return users.get(user_id) # returns str or None
name = find_user(2)
if name is not None:
print(name.upper()) # safe — we checked firstWhy: mypy reads your type hints and reports mismatches without running the code — like a spell-checker for types. Install it and run it over your files.
pip install mypymypy main.py