Python Type Hints and Code Quality · Lesson 133 of 149

Python Type Hints

What you will learn

  • What type hints are, and that Python does not enforce them
  • Annotating variables, parameters and return values
  • Hints for collections: list[str], dict[str, float], tuple[int, int]
  • X | None, Callable, Literal, TypedDict, Final
  • Checking with mypy, and reading its messages
  • Using hints gradually

1. Telling readers and tools what to expect

Python is dynamically typed: a variable can hold any kind of value, and mistakes show up only when the code runs (lesson 2.1). Type hints (also called annotations) let you write down the kinds of values you expect:

def greet(name: str, times: int = 1) -> str:
    return (f"Hello, {name}! " * times).strip()

This says: name is a string, times is an integer (default 1), and the function returns a string. The hints are documentation that tools can check. They help in three ways:

  • Readers see at a glance what a function takes and returns.
  • Editors give better autocompletion and warnings.
  • Checkers such as mypy find mistakes before you run the program.

The most important fact

Python itself ignores type hints when the program runs. They are stored, but never checked:

print(greet("Rina", 2))
print(greet(5))
print(greet.__annotations__)
Hello, Rina! Hello, Rina!
Hello, 5!
{'name': <class 'str'>, 'times': <class 'int'>, 'return': <class 'str'>}

greet(5) passed a number where a string was declared, and Python happily printed Hello, 5!. Only a separate checking tool reports the problem (section 5). Hints are therefore not a way to validate user input (use isinstance and raise for that, lesson 14.4).

Quick check: does Python raise an error when you pass a `str` to a parameter annotated `int`?

No. The annotation is not enforced at run time; a type checker such as mypy reports it.

2. Annotating variables, parameters, returns

age: int = 25
names: list[str] = ["a", "b"]
scores: dict[str, float] = {"a": 1.5}
point: tuple[int, int] = (1, 2)
Hint Meaning
int, float, str, bool, bytes the basic types
list[str] a list whose items are strings
dict[str, float] keys are strings, values are floats
set[int] a set of integers
tuple[int, int] a tuple of exactly two integers
tuple[int, ...] a tuple of any number of integers
X | None an X or None
Iterable[float] anything you can loop over (from collections.abc)
Callable[[int], int] a function taking an int and returning an int
Any "anything": switches checking off for that value

(Since Python 3.9 the built-in list[str] form works; older code used typing.List[str]. Since 3.10, X | None replaces Optional[X].) A function that returns nothing is annotated -> None.

For parameters, prefer general types (Iterable[float], Sequence) and for results the specific one. A function that only loops over its input should accept Iterable[float], so lists, tuples and generators all work (lesson 12.4):

from collections.abc import Callable, Iterable

def total(prices: Iterable[float]) -> float:
    return sum(prices)

def apply(f: Callable[[int], int], x: int) -> int:
    return f(x)

print(apply(lambda n: n + 1, 2), total([1, 2.5]))
3 3.5

(Integers are accepted where float is expected, as Python's number types allow.)

3. Optional values: X | None

Many functions return a value or nothing (None). Say so:

def first(items: list[str]) -> str | None:
    return items[0] if items else None

Now the checker knows that the result might be None and insists you deal with that before using it:

def shout(text: str | None) -> str:
    return text.upper()
error: Item "None" of "str | None" has no attribute "upper"  [union-attr]

The fix is to narrow the type with a check; after it, the checker knows the value is a str:

def safe_shout(text: str | None) -> str:
    if text is None:
        return ""
    return text.upper()

This catches one of the most common runtime errors in Python, AttributeError: 'NoneType' object has no attribute ... (lesson 14.2), without running the code.

4. More precise hints

Literal restricts a value to exact options:

from typing import Literal

Mode = Literal["r", "w"]

def open_it(mode: Mode) -> None: ...

open_it("r")
open_it("x")
error: Argument 1 to "open_it" has incompatible type "Literal['x']"; expected "Literal['r', 'w']"  [arg-type]

TypedDict describes a dictionary with fixed keys:

from typing import TypedDict

class User(TypedDict):
    name: str
    age: int

u: User = {"name": "Rina", "age": "x"}
error: Incompatible types (expression has type "str", TypedDict item "age" has type "int")  [typeddict-item]

Final marks a constant that must not be reassigned:

from typing import Final

MAX: Final = 3
MAX = 4
error: Cannot assign to final name "MAX"  [misc]

Also useful: dataclasses (lesson 13.11) and named tuples (lesson 8.4) are typed records; Self, Protocol and generics are covered in lesson 19.2. A variable that gets the wrong kind of value is also reported:

x: int = "text"
error: Incompatible types in assignment (expression has type "str", variable has type "int")  [assignment]

5. Checking with mypy

mypy is the best-known type checker (others: Pyright, Pyre). Install it into your environment (lessons 16.5 and 16.6) and run it on a file or folder:

python -m pip install mypy
python -m mypy script.py

It reads the code without running it and reports every place where the hints and the code disagree. The messages in this lesson came from mypy 2.4.0 on Python 3.13. They have the form:

file.py:LINE: error: MESSAGE  [error-code]

and the last line says Found N errors in M files, or Success: no issues found. The code in brackets can be searched in the documentation, and an unavoidable false alarm can be silenced on one line with a comment # type: ignore[code] (use sparingly).

By default mypy checks only functions that have annotations, so you can adopt hints gradually. Strict mode (--strict) demands hints everywhere.

Gradual adoption

You do not need to annotate everything. A sensible order:

  1. Annotate the signatures of public functions (parameters and return types).
  2. Annotate variables only where the type is not obvious (names: list[str] = []); mypy infers the rest.
  3. Run mypy in your checks before each commit (lesson 19.3), and fix reports as you go.
  4. Use Any as a last resort.

6. Pros and cons

Benefits Costs
bugs found before running more to type and read
documents the code hints can become out of date if not checked
better editor help complicated hints for very dynamic code
safer refactoring not a substitute for tests

Type hints and tests (lessons 18.2 to 18.4) complement each other: hints catch wrong kinds of values; tests check wrong behaviour.

Worked example: mypy finds two bugs before the program runs

A small stock module uses a dataclass Item and three functions. The code looks reasonable.

from dataclasses import dataclass


@dataclass
class Item:
    name: str
    price: float
    qty: int = 1


def find_item(items: list[Item], name: str) -> Item | None:
    for item in items:
        if item.name == name:
            return item
    return None


def line_total(item: Item) -> float:
    return round(item.price * item.qty, 2)


def price_of(items: list[Item], name: str) -> float:
    item = find_item(items, name)
    return line_total(item)


def cheapest(items: list[Item]) -> str:
    return min(items, key=lambda i: i.price)


stock = [Item("pen", 1.5, 4), Item("book", 12.0)]
print(price_of(stock, "pen"))
print(cheapest(stock))
print(price_of(stock, "ink"))

Running mypy on it, without running the program:

inv.py:24: error: Argument 1 to "line_total" has incompatible type "Item | None"; expected "Item"  [arg-type]
inv.py:28: error: Incompatible return value type (got "Item", expected "str")  [return-value]
Found 2 errors in 1 file (checked 1 source file)

Running the program shows the same two problems in practice:

6.0
Item(name='pen', price=1.5, qty=4)
Traceback (most recent call last):
  File "inv.py", line 34, in <module>
    print(price_of(stock, "ink"))
  File "inv.py", line 24, in price_of
    return line_total(item)
  File "inv.py", line 19, in line_total
    return round(item.price * item.qty, 2)
AttributeError: 'NoneType' object has no attribute 'price'
Report Real problem
line 24: Item | None where Item is expected find_item may return None (for "ink"), and price_of ignores that: the crash on the last line of the program
line 28: returns Item, declared str cheapest actually returns the whole Item, not its name: the output Item(name='pen', ...) is not a name

Fixes: handle the None (raise KeyError(name) or return a default), and return min(...).name in cheapest. After those, mypy reports no issues.

The program run proves the point of the lesson: the second bug did not crash, it just printed the wrong thing, and mypy found it with no test and no run. The stock data is made up.

Common mistakes

  • Believing hints are enforced at run time.
  • Using Any everywhere, which switches the checker off.
  • Hints that lie: annotating -> int but sometimes returning None.
  • Never running a checker, so the hints rot.
  • Over-specific parameter types (list[str] when Iterable[str] would do).
  • Old forms in new code (Optional[...], List[...]) unless you support old Python.
  • Using # type: ignore to silence real problems.
  • Mutable defaults are still wrong with hints (lesson 11.9).

Key takeaways

  • Type hints describe expected types for readers, editors and checkers; Python never enforces them when running.
  • Annotate parameters and return values (def f(x: int) -> str), and variables where needed; use list[str], dict[str, float], X | None, Callable, Literal, TypedDict, Final.
  • A checker such as mypy finds mismatches without running the code, including forgotten None cases.
  • Adopt gradually: public function signatures first.
  • Hints complement tests; they do not replace input validation.

Practice

1. Annotate: a function area(w, h) taking floats and returning a float.

Show answer

def area(w: float, h: float) -> float:

2. What does -> str | None tell a reader?

Show answer

The function returns a string or None, so callers must handle the None case.

3. Why does greet(5) run without error even though name: str?

Show answer

Python does not check annotations at run time; only a type checker like mypy would report it.

4. Which hint describes "a dictionary from names to ages"?

Show answer

dict[str, int].

5. Why prefer Iterable[float] to list[float] for a parameter that is only looped over?

Show answer

It accepts lists, tuples, sets and generators, so the function is more flexible while still type-safe.

6. How does mypy know a value is not None after if x is None: return?

Show answer

It narrows the type after the check: in the rest of the function x is treated as its non-None type.