How type inference works
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.When inference doesn’t work
Mypy will not use type inference in dynamically typed functions (those without a function type annotation):Bidirectional type inference
Type inference is bidirectional and takes context into account. Mypy considers the type of the variable on the left-hand side when inferring the type of the expression on the right-hand side.- Context-aware inference
- Function arguments
[1, 2] is type checked with the context that it’s being assigned to a variable of type list[object].Single statement limitation
Context only works within a single statement. When context would only be available in a following statement, mypy requires an annotation:Empty collections
The type checker cannot always infer the type of an empty list or dictionary. You need to give the type explicitly:Mixed None and non-None values
If you assign both aNone value and a non-None value in the same scope, mypy can infer the combined type:
Mypy uses the first assignment to infer the type, but looks ahead within the same scope to detect
None assignments.Container compatibility
Container types can be unintuitive. Mypy treatslist[int] as incompatible with list[object]:
int:
Other container types like
dict and set behave similarly. See variance for more details.Explicit types override inference
You can override the inferred type using a variable type annotation:Variables without initial values
You can declare the type of a variable without giving it an initial value:Best practices
Annotate function signatures
Annotate function signatures
Always provide type annotations for function parameters and return types. This helps mypy infer types in the function body.
Let mypy infer local variables
Let mypy infer local variables
Usually you don’t need to annotate local variables if mypy can infer their types correctly from assignments.
Annotate empty collections
Annotate empty collections
Always provide explicit type annotations for empty lists, dictionaries, and other collections.
Use reveal_type for debugging
Use reveal_type for debugging
Use
reveal_type() to see what type mypy has inferred during development.