Skip to content
BIASED

Type hints

Block 1 of 8~2 min

Types in prose

The topic Modules, packages and environments ended with a project whose pyproject.toml lists every dependency and its version, so anyone can install what the code needs. The functions inside the project still do not say what they need. Does tax take a float or a string? Can find return None? Which keys must a config dict have? A reader learns it from the docstring, from the body, or from a crash.

Here is the docstring way. find looks a word up in a small vocabulary:

def find(words, target):
    """Return the position of target in words (a list of str), or None."""
    for i, w in enumerate(words):
        if w == target:
            return i
    return None
 
vocab = ["the", "cat", "sat"]
print(find(vocab, "cat") + 1)
print(find(vocab, "dog") + 1)

The traceback is shortened:

2
Traceback (most recent call last):
  ...
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

The docstring warned that None can come back, and nothing read the docstring. The + 1 line works on every run where the word is in the list and fails on the first day it is not.

Type hints write the same facts into the code in a notation that tools can read:

def find(words: list[str], target: str) -> int | None: ...

A type checker is a separate program that reads the source code and reports where it disagrees with the hints, without running anything. This topic shows what Python 3.14 itself does with hints (very little, and later than before), how to write the types that come up in ML code, and what a checker, mypy, finds before the program runs.

Answers are saved on the server and tied to this browser until you sign in.