Overview
Mypy’s type system allows you to add type annotations to your Python code to catch errors before runtime. Type annotations specify what types of values variables, function parameters, and return values can have.Type inference
For most variables, if you don’t explicitly specify a type, mypy will infer the correct type based on what is initially assigned to the variable.Mypy will not use type inference in dynamically typed functions (those without a function type annotation) — every local variable type defaults to
Any in such functions.Explicit type annotations
You can override the inferred type of a variable by using a variable type annotation:x would be just int. The annotation gives it a more general type int | str.
Function annotations
Explicit types for collections
The type checker cannot always infer the type of a list or dictionary. You may need to provide explicit type annotations:Using type arguments (e.g.,
list[int]) on builtin collections only works in Python 3.9+. For Python 3.8 and earlier, use List[int], Dict[str, int], etc. from the typing module.Context in type inference
Type inference is bidirectional and takes context into account. Mypy will consider the type of the variable on the left-hand side when inferring the type of the expression on the right:The reveal_type function
Use reveal_type() to see what type mypy has inferred for an expression:
Silencing type errors
You can disable type checking on specific lines using# type: ignore comments:
Best practices
Always annotate function signatures
Always annotate function signatures
Even if mypy can infer types, explicit annotations make your code more readable and help catch errors earlier.
Use the most specific type possible
Use the most specific type possible
Instead of
list[object], use list[str] if you know the list contains strings.Avoid overusing Any
Avoid overusing Any
The
Any type disables type checking. Use it sparingly and only when necessary.Let mypy infer local variable types
Let mypy infer local variable types
You usually don’t need to annotate local variables if mypy can infer their types correctly.