Local type inference
Once you have added type hints to a function (i.e. made it statically typed),mypy will automatically type check that function’s body. While doing so,mypy will try and infer as many details as possible.
We saw an example of this in the normalize_id
function above – mypy understandsbasic isinstance
checks and so can infer that the user_id
variable was oftype int
in the if-branch and of type str
in the else-branch. Similarly, mypywas able to understand that name
could not possibly be None
in the greeting
function above, based both on the name is None
check and the variable assignmentin that if statement.
As another example, consider the following function. Mypy can type check this functionwithout a problem: it will use the available context and deduce that output
must beof type List[float]
and that num
must be of type float
:
- def nums_below(numbers: Iterable[float], limit: float) -> List[float]:
- output = []
- for num in numbers:
- if num < limit:
- output.append(num)
- return output
Mypy will warn you if it is unable to determine the type of some variable –for example, when assigning an empty dictionary to some global value:
- my_global_dict = {} # Error: Need type annotation for 'my_global_dict'
You can teach mypy what type my_global_dict
is meant to have by giving ita type hint. For example, if you knew this variable is supposed to be a dictof ints to floats, you could annotate it using either variable annotations(introduced in Python 3.6 by PEP 526) or using a comment-basedsyntax like so:
- # If you're using Python 3.6+
- my_global_dict: Dict[int, float] = {}
- # If you want compatibility with older versions of Python
- my_global_dict = {} # type: Dict[int, float]