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 greetingfunction 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:

  1. def nums_below(numbers: Iterable[float], limit: float) -> List[float]:
  2. output = []
  3. for num in numbers:
  4. if num < limit:
  5. output.append(num)
  6. 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:

  1. 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:

  1. # If you're using Python 3.6+
  2. my_global_dict: Dict[int, float] = {}
  3.  
  4. # If you want compatibility with older versions of Python
  5. my_global_dict = {} # type: Dict[int, float]