Sub topic 1
What static type checking is and why Python has it
Python is a dynamically typed language. Every value has a type at runtime, but nothing checks that a function receives the type its author expected until that line runs. Static type checking adds a separate tool that reads your source code, compares the types it finds, and reports mismatches before the program starts. This chapter explains how that works, why Python gained it, and what it can and cannot promise.
Prerequisites
This chapter assumes you can:
- Write and run Python 3 functions, classes, and modules.
- Install packages with pip inside a virtual environment.
- Use a terminal to run commands.
- Use Python 3.10 or newer, so that the
str | Nonesyntax works at runtime.
You do not need any prior experience with type annotations.
Dynamic typing and where its bugs surface
In Python, a name is not tied to a type. The same variable can hold an integer on one line and a string on the next. The interpreter only complains when an operation fails on the actual value.
def greet(name):
return "Hello, " + name
print(greet("Ada"))
print(greet(42))The first call prints Hello, Ada. The second raises TypeError: can only concatenate str (not "int") to str. The bug is in the second call, but you learn about it only if execution reaches that line. In a large program, that line might sit in a rarely used branch, such as an error handler or an admin command. The failure then appears in production.
Tests catch some of these bugs, but a test only covers the paths it exercises. A static checker examines every path in the code it analyzes, without running any of it.
What a static type checker does
A static type checker is a program that analyzes your source without executing it. It works in roughly three steps:
- It parses your files and builds a model of every function, class, and variable.
- It records the types you declared in annotations and infers the types you left out.
- It checks each operation against those types and reports any that cannot be valid.
The checker and the interpreter are independent tools. The checker never runs your code, and the interpreter never enforces the checker's rules.
A first example
Annotations are the type declarations you write in the code. Here is the same function with annotations added.
def greet(name: str) -> str:
return "Hello, " + name
greet("Ada")
greet(42) # flagged by the checker: int is not strThe annotation name: str says the parameter is a string. The annotation -> str says the function returns a string. A checker such as mypy or Pyright reports the call greet(42) as an error, because int is not compatible with str. It reports this without running the program.
The two checkers you will use in this tutorial are:
- mypy, the original checker, maintained by the Python community.
- Pyright, a checker from Microsoft that also powers the Pylance extension in VS Code.
Both read the same annotation syntax, but they are separate programs and they do not always agree. A later chapter compares them in detail.
Why Python has it
Python's type system was added in steps rather than designed up front.
- Python 3.0 allowed arbitrary annotation syntax on function parameters, but gave it no meaning.
- PEP 484 (Python 3.5) defined what annotations should mean for type checking, and added the
typingmodule. - Later PEPs added variable annotations,
Protocol,TypedDict, and theX | Yunion syntax that this tutorial uses.
The motivation was large codebases. In a project with hundreds of thousands of lines, no one can hold every function's expected inputs in their head. Annotations document those expectations in a form a tool can verify. They also let editors offer reliable completion and safe renames, because the editor knows what type each expression has.
Python kept dynamic typing as the default. Type checking is optional, which leads to the next idea.
Gradual typing
Python uses gradual typing: you can annotate some parts of a program and leave others untyped. The checker verifies what it has information about and is lenient about the rest. A value whose type is unknown is treated as Any, which the checker accepts everywhere.
This design lets you add annotations one function or module at a time, in a codebase that already works. It also means a clean checker run proves less in a partly annotated project than in a fully annotated one. A later chapter covers Any and how strict mode closes these gaps.
What the checker cannot guarantee
The most common mistake at this level is to treat annotations as runtime enforcement. They are not. The interpreter stores them and ignores them.
def add(a: int, b: int) -> int:
return a + b
print(add("x", "y"))Run with plain python, this prints xy. No error occurs, even though the annotations say the arguments must be integers. Only a checker run would flag the call.
A checker also cannot know what arrives from outside the program. Consider this code.
import json
def read_age(raw: str) -> int:
return json.loads(raw)
print(read_age('"thirty"'))The checker accepts this, because json.loads is declared to return Any. At runtime the function returns the string thirty while claiming to return an int. The annotation is a promise you made, and nothing verified it. Data from files, networks, databases, and user input needs explicit validation at the boundary, using code or a library built for that purpose.
The following table summarizes what static checking covers.
| Question | Does a static checker answer it? |
|---|---|
| Do I pass the wrong type of argument to a function I annotated? | Yes |
| Can this variable be `None` where I call a method on it? | Yes |
| Does this call use an attribute or method that does not exist? | Yes, when the type is known |
| Does external data match the type I declared? | No, it needs runtime validation |
| Is the algorithm correct? | No, that needs tests |
| Is a value of type `Any` safe to use? | No, the checker stops checking it |
Common errors in how people use checkers
- Expecting runtime errors from annotations. Annotations do not raise exceptions. If you want runtime enforcement, you need a validation library or explicit
isinstancechecks. - Reading a clean run as proof of correctness. A checker with no errors means no detected type mismatches in the code it could analyze. Untyped functions and
Anyvalues reduce what it can detect. - Annotating everything with
Anyto silence errors. This removes the checker's information instead of fixing the problem. Later chapters cover targeted alternatives. - Running only one tool and assuming the result holds for both. The two checkers can disagree on edge cases, so know which one your project treats as authoritative.
What comes next
The next chapter covers the annotation syntax for functions, variables, and class attributes. After that you will install both checkers and run them from the command line. The ideas in this chapter apply throughout: the checker reasons about code without running it, annotations are promises rather than enforcement, and gradual typing lets you adopt all of this at your own pace.
Exercise
A teammate writes def total(prices: list[float]) -> float: and calls total(["1", "2"]). They run the script with python script.py, and it finishes without any type error. Does that mean the call is valid? Explain what would reveal the problem.
Show answer
No. The interpreter ignores annotations, so running the script never compares the arguments to the declared types. The call passes a list of strings where a list of floats was declared, and a static checker such as mypy or Pyright would report it when run on the file, without executing it. Whether the script then fails at runtime depends on what total does with the strings. Summing them with sum would raise a TypeError.
Exercise
A function is annotated -> int but returns the result of json.loads(raw). The checker reports no errors. Why, and what should you do if the input might not be a number?
Show answer
json.loads is declared to return Any, and the checker does not check values of type Any, so the return passes. The annotation is therefore not verified. If the input might not be an integer, validate it at runtime, for example with isinstance(value, int) and a raised error otherwise, before returning it.