Reading history

Python Type Hints: Annotations, Optional, TypedDict and mypy

5 min read 2 views

Learn Python type hints: annotating functions and variables, list[int] and dict types, X | None, Callable, Literal, TypedDict, type aliases, generics and mypy.

Type hints are annotations that say what kind of value a variable, parameter or return value should hold, such as name: str or -> float. Python does not enforce them when the program runs, but editors and tools such as mypy use them to catch mistakes before you run the code, and they make functions self-documenting. This lesson covers the basic syntax and the most useful types from modern Python.

In this lesson you will learn

  • Annotating parameters, return values and variables
  • Built-in generic types: list[int], dict[str, float], tuple
  • Optional values with X | None
  • Callable, Literal and TypedDict
  • Type aliases and generic functions (Python 3.12+)
  • Checking hints with a static type checker

Basic Annotations

def average(marks: list[float]) -> float:
    return sum(marks) / len(marks)

def greet(name: str, times: int = 1) -> str:
    return " ".join([f"Hi {name}!"] * times)

def find(names: list[str], target: str) -> int | None:
    return names.index(target) if target in names else None

print(average([3.5, 3.9, 3.2]))
print(greet("Nadia", 2))
print(find(["a", "b"], "b"), find(["a", "b"], "z"))

scores: dict[str, int] = {"Rafi": 64, "Mitu": 91}
point: tuple[int, int] = (3, 4)
print(scores, point)

# Hints are not enforced at run time
print(greet(42))                       # runs, though a checker would complain
print(average.__annotations__)

Output

3.533333333333333
Hi Nadia! Hi Nadia!
1 None
{'Rafi': 64, 'Mitu': 91} (3, 4)
Hi 42!
{'marks': list[float], 'return': <class 'float'>}
  • marks: list[float] says the parameter should be a list of floats, and -> float gives the return type.
  • Since Python 3.9 the built-in types can be used directly: list[str], dict[str, int], tuple[int, int]. Older code imports List and Dict from typing.
  • int | None (Python 3.10+) means “an int or None”. It is the same as the older Optional[int].
  • Variables can be annotated too: scores: dict[str, int] = {...}.
  • Hints are not checked at run time. greet(42) runs happily even though name should be a str. Hints are stored in __annotations__ and read by tools.

More Precise Types

from typing import Callable, TypedDict, Literal, Any

class Student(TypedDict):
    name: str
    cgpa: float

def best(students: list[Student]) -> Student:
    return max(students, key=lambda s: s["cgpa"])

def apply(fn: Callable[[int], int], value: int) -> int:
    return fn(value)

Mode = Literal["r", "w", "a"]
def open_mode(mode: Mode) -> str:
    return {"r": "read", "w": "write", "a": "append"}[mode]

type Matrix = list[list[float]]           # type alias (Python 3.12+)
def size(m: Matrix) -> tuple[int, int]:
    return len(m), len(m[0])

def first[T](items: list[T]) -> T:        # generic function (Python 3.12+)
    return items[0]

print(best([{"name": "Tania", "cgpa": 3.95}, {"name": "Arif", "cgpa": 3.41}]))
print(apply(lambda n: n * n, 9))
print(open_mode("a"), size([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]))
print(first(["x", "y"]), first([10, 20]))

Output

{'name': 'Tania', 'cgpa': 3.95}
81
append (3, 2)
x 10
  • TypedDict describes a dictionary with fixed keys and value types, which is common for JSON-like data.
  • Callable[[int], int] describes a function that takes an int and returns an int, so you can type arguments such as callbacks and lambdas.
  • Literal["r", "w", "a"] allows only those exact values; a checker flags open_mode("x").
  • type Matrix = list[list[float]] creates a readable type alias.
  • def first[T](items: list[T]) -> T is a generic function: whatever type the list holds, the result has the same type.
  • Use Any only when a value can truly be anything; it switches checking off for that value.

Checking Your Hints

python -m pip install mypy
mypy hints.py

For the greet(42) call above, mypy reports an error along the lines of: Argument 1 to “greet” has incompatible type “int”; expected “str”. Editors such as VS Code (with Pylance) show the same warnings as you type. Install tools inside a virtual environment.

HintMeaning
int, str, float, boolSimple types
list[int], set[str]Collection of one element type
dict[str, float]Keys and values
tuple[int, str], tuple[int, ...]Fixed or variable length tuple
X | NoneX or None
Callable[[A, B], R]Function from A, B to R

Common Mistakes

  1. Believing hints validate input; check data yourself or use a library such as pydantic.
  2. Using list[int] on Python 3.8 or older, which raises an error; use typing.List there.
  3. Forgetting | None on a function that can return None.
  4. Overusing Any, which hides the mistakes hints are meant to catch.

Practice Exercises

Exercise 1. Add type hints to def word_count(text): return len(text.split()).

Show answer
def word_count(text: str) -> int:
    return len(text.split())

Exercise 2. Annotate a function that takes a dictionary of names to marks and returns the top name, or None if the dictionary is empty.

Show answer
def top(marks: dict[str, int]) -> str | None:
    return max(marks, key=marks.get) if marks else None

Frequently Asked Questions

Do type hints make Python faster?

No. The standard interpreter ignores them when running code. Their value is in catching bugs early and documenting intent.

Do I have to annotate everything?

No. Hints are optional and can be added gradually. Start with public functions, where they help callers most.

Summary

  • Write param: type and -> return_type to annotate functions.
  • Use built-in generics like list[int] and unions like str | None.
  • TypedDict, Callable and Literal describe data precisely.
  • Python does not enforce hints; run mypy or rely on your editor to check them.

Next: Python Dataclasses.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *