Sub topic 1
Type hints and what a type checker does
Prerequisites
This chapter assumes you can write Python functions and classes. It also assumes you have seen annotations such as list[int] and str | None. You don't need to have run a type checker yet. Later chapters assume you are comfortable with the ideas here.
What a type hint is
A type hint is an annotation that states which type a variable, parameter, or return value is meant to have. Python records hints but does not enforce them when the program runs.
def total_length(words: list[str]) -> int:
return sum(len(w) for w in words)
print(total_length(["a", "bb"])) # 3
print(total_length(("a", "bb"))) # 3, runs fine even though a tuple is not a listThe second call breaks the hint, yet the interpreter accepts it because a tuple of strings works with this code. The hint is a claim about intent, and only a separate tool checks it.
What a type checker does
A static type checker, such as mypy or pyright, reads your source without running it. It works in three steps:
- It reads the annotations you wrote.
- It infers a type for every expression it can, such as
count = 0being anint. - It checks that each call, assignment, and
returnis compatible with those types, then reports mismatches.
count = 0
count = "many" # checker error: str is not compatible with int
def shout(text: str) -> str:
return text.upper()
shout(42) # checker error: argument 1 has type int, expected strBoth errors appear before the program starts. This is the main benefit of hints: mistakes show up in your editor or CI run instead of in production.
Where plain hints fall short
A checker can only reason about what the hints say. Consider a function that returns the first item of a list. What should its hints be?
from typing import Any
def first_item(items: list[Any]) -> Any:
return items[0]
n = first_item([1, 2, 3])
n.upper() # no checker error, but this raises AttributeError at runtimeAny tells the checker to stop checking. The result n is really an int, but the checker has lost that fact, so the mistake slips through. Writing -> int would be wrong for a list of strings. Writing -> int | str forces every caller to handle cases that cannot happen.
What we want to say is: "this function returns whatever type the list holds." The checker needs a way to connect the type of the input to the type of the output. That connection is what a generic is, and it is the subject of the next chapter.
Summary of the model
- Hints are annotations. Python stores them and does not enforce them.
- A static checker reads hints and infers types, then reports mismatches without running the code.
Anyswitches checking off for a value, so it hides errors.- Generics let one definition work with many types while the checker still tracks which type is in play.
Exercise
A teammate writes def double(x: int) -> int: return x * 2 and then calls double("ab"). The program prints abab and raises no exception. Does the type hint mean the code is correct? What would a static checker report, and when?
Show answer
No. The hint is not enforced at runtime, so "ab" * 2 runs and gives abab. A static checker such as mypy or pyright would report that the argument has type str where int is expected. It reports this before the program runs, when you run the checker or when your editor analyses the file.
Exercise
Why is -> Any a poor return type for first_item, and what is missing from Python's hints that would let the checker do better?
Show answer
Any makes the checker stop tracking the value, so mistakes such as calling .upper() on an int go unreported. What is missing is a way to say that the return type equals the element type of the input list. Generics, introduced in the next chapter, provide this.