Sub topic 1
What static type checking is and why Python has it
Prerequisites
This chapter assumes that you can write and run Python 3 functions and modules, install packages in a virtual environment, and use a command line. You also need Python 3.10 or newer.
Static type checking
Python checks most types while the program runs. A static type checker examines source code before execution. It compares the types you declare or imply with how values are used.
Static checking can catch an integer passed where a string is expected. It cannot prove that a network request will succeed or that a function always receives trustworthy external data. Annotations guide the checker; they do not add runtime validation.
Annotating functions and variables
A type annotation states the intended type of a value. Function annotations describe parameters and the return value. Variable annotations document attributes and local or global variables.
def greet(name: str) -> str:
return "Hello, " + name
count: int = 3
greet("Ada")
greet(42) # reported by a checkerThe second call is not automatically rejected by Python. A checker reports it before the program runs.
Running mypy and Pyright on your code
mypy and Pyright are separate static type checkers. Install them in the project’s virtual environment and check the source directory:
python -m pip install mypy pyright
mypy src/
pyright src/Both commands normally return a non-zero status when they find errors, which makes them suitable for continuous integration.
Inference and `reveal_type`
A checker often infers a type without an annotation. reveal_type asks the checker to print its inference. It is a checking aid, not a normal runtime operation.
items = [1, 2, 3]
reveal_type(items) # list[int]
name = "Ada"
reveal_type(name) # strInference reduces repetitive annotations, while explicit annotations clarify public interfaces.
Union types and optional values
A union means that a value may have more than one type. str | None means either a string or the special value None.
def shout(name: str | None) -> str:
if name is None:
return ""
return name.upper()The None check narrows name to str in the remaining branch. Without that check, a checker warns because None has no upper method.
Exercise
What type does the checker know for name after the if name is None branch returns?
Show answer
It knows that name is str, so calling name.upper() is safe according to the annotation.