Skip to main content
Albero Academy

Type Hints

Annotate types for better tooling, editor help and fewer bugs.

Advanced Python10 min

Type hints annotate the types your functions and variables expect. Python doesn't enforce them at runtime — they're for humans and tools. Editors use them for autocomplete and warnings, and a type checker like mypy catches whole classes of bugs before you run the code.

Annotating functions

parameter and return types
def greet(name: str, times: int = 1) -> str:
return f"Hi {name}! " * times
# Variables can be annotated too
count: int = 0
names: list[str] = []

Containers & optionals

Use the built-in generics for containers, and the | union for "either type":

richer types
def totals(scores: dict[str, int]) -> list[int]:
return list(scores.values())
def find(users: list[dict], uid: int) -> dict | None: # dict OR None
...
# Older syntax you'll still see:
from typing import Optional, Union
x: Optional[int] # same as int | None
y: Union[int, str] # same as int | str

Checking with mypy

Key takeaways

  1. 01Type hints annotate parameter, return and variable types.
  2. 02They are not enforced at runtime — they power editors and type checkers.
  3. 03Use built-in generics: list[int], dict[str, int]; use | for unions.
  4. 04X | None (or Optional[X]) means "X or None".
  5. 05Run mypy to catch type bugs statically; adopt hints gradually.

Finished this chapter?

Mark it complete to track your progress through Python.