The essentials of module 12 on one page. Every runnable block on this page is checked against its output. Hints are for Python 3.12+.
I want to…
Use…
Example
hint a parameter and the return value
name: type, -> type
def mean(xs: list[float]) -> float:
say “returns nothing”
-> None
def log(msg: str) -> None:
hint an empty container
a variable annotation
rows: list[dict[str, str]] = []
allow a missing value
X | None
def find(id: str) -> Customer | None:
allow one of several types
a union
value: int | float | str
accept any read-only sequence
Sequence[T]
def mae(y: Sequence[float], p: Sequence[float])
accept anything you can loop over
Iterable[T]
def total(xs: Iterable[float]) -> float:
type a generator
Iterator[T]
def read_rows(p: Path) -> Iterator[str]:
type a function argument
Callable[[A, B], R]
metric: Callable[[list[float]], float]
allow only some constants
Literal[...]
strategy: Literal["mean", "median"]
type a JSON record
TypedDict
class Order(TypedDict): amount: float
mark an optional key
NotRequired[T]
phone: NotRequired[str | None]
name a long type
type alias
type Matrix = list[list[float]]
keep the item type through a function
a type parameter
def first[T](xs: Sequence[T]) -> T:
make a container class generic
class C[T]:
class Window[T]:
limit a type parameter
a bound
def top[N: float](xs: list[N]) -> N:
accept “anything with method m”
Protocol
class Model(Protocol): def predict(...)
use isinstance with a protocol
@runtime_checkable
isinstance(obj, Model)
return the object’s own class
Self
def fit(self, X) -> Self:
tell the checker a type you know
cast(T, value)
cast(Page, json.load(f))
give one function several signatures
@overload
see Overloads
ask the checker for a type
reveal_type(x)
reveal_type(first(ids))
silence one checker error
# type: ignore[code]
x = old() # type: ignore[no-untyped-call]
read hints at runtime
typing.get_type_hints
get_type_hints(Order)
list the values of a Literal
typing.get_args
get_args(Plan.__value__)
check a file
mypy file.py
mypy clean.py
check strictly
mypy --strict
mypy --strict src/
def line_revenue (quantity: int , unit_price: float , discount: float = 0.0 ) -> float :
return round (quantity * unit_price * ( 1 - discount), 2 ) # params, default, return
def warn (message: str ) -> None : # returns nothing
values: list[ float ] = [] # an empty container needs a hint
total = line_revenue( 3 , 249 , 0.1 ) # inferred as float; int is accepted as float
print (line_revenue. __annotations__ [ "return" ])
Where
Syntax
Note
parameter
x: int
with default: x: int = 0 (spaces around =)
*args
*args: float
each positional argument is a float
**kwargs
**kwargs: str
each keyword value is a str
return
-> float
-> None for “returns nothing”
variable
n: int = 0
only when inference is not enough
attribute
self.items: list[T] = []
in __init__
class-level constant
RATE: Final = 0.2
Final from typing: never reassigned
Hint
Accepts
Notes
int, float, bool, str, bytes
that type
int passes as float; bool passes as int
list[float]
a list of floats
invariant: list[int] is not a list[float]
dict[str, list[int]]
dict of str → list of int
invariant in the value type
set[str], frozenset[str]
sets
tuple[str, float]
exactly 2 items
fixed-length record
tuple[float, ...]
any length, all floats
Sequence[float]
list, tuple, range, str
read-only, covariant: accepts list[int]
Iterable[float]
anything you can loop over
lists, generators, files
Iterator[str]
an iterator
generator return type
Mapping[str, float]
dicts, read-only
covariant in the value
MutableMapping[str, float]
dicts you may change
Callable[[A, B], R]
functions, lambdas, methods
Callable[..., R] = any parameters
type[Model]
a class, not an instance
def build(cls: type[Model]) -> Model:
object
anything; allows nothing until narrowed
safe “any”
Any
anything; allows everything
turns checking off
Import the abstract types from collections.abc: from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence. Import the rest from typing. Old spellings (typing.List, Dict, Optional[X], Union[A, B]) still work; write list, dict, X | None, A | B.
Rule of thumb: accept general, return specific . Parameters Iterable, Sequence, Mapping; return values list, dict.
def discount_rate (code: str | None ) -> float :
if code is None : # narrows code to str below
return 0.2 if code.upper() == "BLACKFRIDAY" else 0.05
def as_float (value: object ) -> float :
if isinstance (value, bool ) or not isinstance (value, int | float | str ):
raise TypeError ( f "not a number: { value !r } " ) # value is int | float | str below
print (discount_rate( None ), discount_rate( "blackfriday" ), as_float( "21.5" ))
Check
Narrows x: str | None to
Note
if x is None: return
str after the if
the clearest form
if x is not None:
str inside
if x:
str inside
also drops "": careful with 0, 0.0
isinstance(x, str)
str inside
works for any union
assert x is not None
str after
for “cannot happen” cases
[v for v in xs if v is not None]
list[str]
filter a list of optionals
"key" in record
the TypedDict with the key
for NotRequired keys
from collections.abc import Callable
from typing import Literal
type Metric = Callable[[list[ float ], list[ float ]], float ]
def mae (y: list[ float ], p: list[ float ]) -> float :
return sum ( abs (a - b) for a, b in zip (y, p, strict = True )) / len (y)
def evaluate (y: list[ float ], p: list[ float ], metric: Metric = mae) -> float :
return round (metric(y, p), 3 )
def impute (xs: list[ float | None ], how: Literal[ "zero" , "drop" ]) -> list[ float ]:
return [x for x in xs if x is not None ]
return [ 0.0 if x is None else x for x in xs]
print (evaluate([ 3.0 , 5.0 ], [ 2.5 , 5.5 ]), impute([ 1.0 , None ], "zero" ))
Form
Meaning
Callable[[float], float]
one float in, a float out
Callable[[], None]
no parameters, returns nothing (a callback)
Callable[..., float]
any parameters; avoid when you know them
Callable[P, R] with [**P, R]
“same signature as the wrapped function” in decorators
Literal["a", "b"]
only these strings
Literal[429], Literal[True]
one fixed int or bool
get_args(Alias.__value__)
the values of a type alias of a Literal at runtime
from typing import NotRequired, TypedDict
class Address ( TypedDict ):
postal_code: NotRequired[ str ] # key may be absent
class Customer ( TypedDict ):
phone: NotRequired[ str | None ] # absent or null
"address" : { "city" : "Chicago" , "region" : "North" },
print (c[ "address" ].get( "postal_code" , "unknown" ), "phone" in c, type (c). __name__ )
print ( sorted (Customer.__required_keys__), sorted (Customer.__optional_keys__))
['address', 'customer_id'] ['phone']
Need
Write
all keys required (default)
class R(TypedDict): ...
one optional key
key: NotRequired[T]
all keys optional, one required
class R(TypedDict, total=False): plus key: Required[T]
key present, value may be null
key: T | None
key may be absent or null
key: NotRequired[T | None]
a key name that is not an identifier
R = TypedDict("R", {"user-id": str})
extend a record
class Paid(Order): paid_at: str
load JSON into it
cast(R, json.load(f)), after validation for untrusted data
from typing import NewType
CustomerId = NewType( "CustomerId" , str ) # a distinct type for the checker only
def lookup (customer_id: CustomerId) -> str :
return f "looking up { customer_id } "
cid = CustomerId( "C00001" ) # at runtime it is just the str
print (lookup(cid), type (cid). __name__ , Matrix.__value__)
looking up C00001 str list[Row]
Form
Use
type Matrix = list[list[float]]
a short name; same type to the checker (Python 3.12+)
type Pair[T] = tuple[T, T]
a generic alias
Matrix = list[list[float]]
old alias form, still common
UserId = NewType("UserId", int)
a different type for the checker: a plain int is rejected
from collections.abc import Sequence
def first[T](items: Sequence[T]) -> T:
def largest[N: float ](values: Sequence[N]) -> N: # bound: float, int or bool
def invert[K, V](mapping: dict[K, V]) -> dict[V, K]:
return {v: k for k, v in mapping.items()}
def __init__ (self, item: T) -> None :
print (first(( "C00001" , "C00002" )), largest([ 3 , 25 , 1 ]), invert({ "a" : 1 }), Box( 2.5 ).item)
PEP 695 (3.12+)
Older form
def f[T](x: T) -> T:
T = TypeVar("T") then def f(x: T) -> T:
def f[N: float](...)
N = TypeVar("N", bound=float)
def f[S: (str, bytes)](...)
S = TypeVar("S", str, bytes) (constrained)
class Box[T]:
class Box(Generic[T]):
def deco[**P, R](f: Callable[P, R]) -> Callable[P, R]:
P = ParamSpec("P"), R = TypeVar("R")
type Pair[T] = tuple[T, T]
Pair = tuple[T, T] with a module-level T
Box[float](...)
the same: a type argument at creation
from typing import Protocol, Self, runtime_checkable
class Regressor ( Protocol ):
def fit (self, X: list[list[ float ]], y: list[ float ]) -> Self: ...
def predict (self, X: list[list[ float ]]) -> list[ float ]: ...
class MeanRegressor : # no inheritance: it matches by shape
def fit (self, X: list[list[ float ]], y: list[ float ]) -> Self:
self .mean_ = sum (y) / len (y)
def predict (self, X: list[list[ float ]]) -> list[ float ]:
return [ self .mean_ for _ in X]
model = MeanRegressor().fit([[ 1.0 ], [ 2.0 ]], [ 10.0 , 20.0 ])
print (model.predict([[ 3.0 ]]), isinstance (model, Regressor), isinstance ( 42 , Regressor))
Protocol
Abstract base class (abc.ABC)
Typing style
structural: matches by shape
nominal: must inherit
Third-party classes
match without changes
must be registered or wrapped
Runtime isinstance
only with @runtime_checkable; checks names only
yes, real inheritance
Shared code
none (a pure description)
can provide method implementations
Use for
plug-in points, “anything with .read()”
a family of classes you own
from typing import cast, overload
def to_f (c: float ) -> float : ...
def to_f (c: list[ float ]) -> list[ float ]: ...
def to_f (c: float | list[ float ]) -> float | list[ float ]:
return [ round (x * 9 / 5 + 32 , 1 ) for x in c]
return round (c * 9 / 5 + 32 , 1 )
same = cast(list[ float ], raw) # no check and no conversion
print (to_f( 21.5 ), to_f([ 21.0 , 21.9 ]), same is raw, same)
70.7 [69.8, 71.4] True ['21.0']
Tool
Does
At runtime
cast(T, v)
makes the checker treat v as T
returns v unchanged
@overload
several signatures for one function
only the last (real) definition runs
reveal_type(x)
checker prints the inferred type
prints the runtime type to stderr
assert_never(x)
checker proves a branch cannot happen
raises if reached
TYPE_CHECKING
if TYPE_CHECKING: imports for hints only
False
Self
“this class” in methods
Final
a constant that must not be reassigned
no effect
ClassVar[int]
a class attribute, not per instance
no effect
from typing import Literal, TypedDict, get_args, get_type_hints
type Role = Literal[ "admin" , "analyst" ]
bad: User = { "id" : "7" , "roles" : [ "owner" ]} # runs: hints are not checked
print (bad[ "id" ], get_type_hints(User)[ "id" ], get_args(Role), get_args(Role.__value__))
7 <class 'int'> () ('admin', 'analyst')
Fact
Consequence
Python stores hints and ignores them
wrong types run; silent wrong results are possible
json.load, csv and HTTP data arrive as Any or str
the checker cannot see their real content
cast checks nothing
validate untrusted data first
some libraries read hints at runtime
pydantic, FastAPI, dataclasses and Typer act on them
TypeAdapter(User).validate_python(d) (pydantic)
full runtime validation from the same TypedDict
Command
Does
mypy file.py
check one file (and the modules it imports)
mypy src/ tests/
check folders
mypy --strict file.py
all strict checks: hints required, no Any leaks, unused ignores
mypy --check-untyped-defs old.py
also check the bodies of functions without hints
mypy --pretty file.py
show the source line with ^~~~ markers
mypy --python-version 3.12 file.py
check against an older Python
mypy --ignore-missing-imports
quiet “missing library stubs” for untyped packages
pyright file.py
Microsoft’s checker (also in VS Code’s Pylance)
strict = true # same as --strict for every run
module = [ "sklearn.*" ] # a library without type hints
ignore_missing_imports = true
Common error codes:
Code
Meaning
Typical fix
arg-type
an argument has the wrong type
convert, or fix the hint
return-value
the returned value does not match ->
return the right type, or widen the hint (| None)
assignment
a value does not fit the variable’s type
union-attr
an attribute used on X | None
narrow with is None first
typeddict-item
unknown key or wrong value in a TypedDict
fix the key name or value
index
wrong key type for a dict or Literal key
dict-item
a dict literal entry has the wrong type
call-overload
no overload matches
no-untyped-def
a function without hints (strict)
add hints
no-untyped-call
typed code calls an untyped function (strict)
add hints to the callee
no-any-return
returns Any from a typed function (strict)
cast or validate
var-annotated
needs a type for an empty container
xs: list[float] = []
import-untyped
a library without type hints
install its stubs, or ignore it in config
Read a line: file.py:27: error: <message> [code]. The last line says Found N errors in M files or Success: no issues found.
Hints do not run. count: int = "3" works at runtime. Only a checker or a runtime validator finds the problem.
mypy says Success on untyped code because it skips unannotated function bodies. Use --strict or --check-untyped-defs.
list[int] is not a list[float] (invariance). Accept Sequence[float] for read-only input.
dict.get() returns X | None. As a sort key (key=d.get), mypy rejects it; use key=lambda k: d[k].
if x: narrows away None but also 0, 0.0 and "". Use is not None for numbers.
mypy does not warn when you read a NotRequired key with []. pyright’s docs list a rule for it (reportTypedDictNotRequiredAccess). Use .get() or in.
cast is a promise without a check. A false cast silences the checker and keeps the bug.
get_args(Alias) on a type alias returns (). Use get_args(Alias.__value__).
isinstance with a @runtime_checkable protocol checks only that the method names exist.
bool is a subtype of int: isinstance(True, int) is True. Test for bool first when it matters.
json.load returns Any: everything that comes from it is unchecked until you cast or validate.
A bare # type: ignore hides all future errors on that line. Always write the code: # type: ignore[arg-type].
The PEP 695 syntax (def f[T], class C[T], type X = ...) needs Python 3.12+. Older projects use TypeVar, Generic and TypeAlias.
Libraries without hints (for example scikit-learn) give an import-untyped error, and their values are Any. Configure an override in pyproject.toml instead of sprinkling ignores.