Complex type tests

Mypy can usually infer the types correctly when using isinstancetype tests, but for other kinds of checks you may need to add anexplicit type cast:

  1. def f(o: object) -> None:
  2. if type(o) is int:
  3. o = cast(int, o)
  4. g(o + 1) # This would be an error without the cast
  5. ...
  6. else:
  7. ...

Note

Note that the object type used in the above example is similarto Object in Java: it only supports operations defined for _all_objects, such as equality and isinstance(). The type Any,in contrast, supports all operations, even if they may fail atruntime. The cast above would have been unnecessary if the type ofo was Any.

Mypy can’t infer the type of o after the type() checkbecause it only knows about isinstance() (and the latter is betterstyle anyway). We can write the above code without a cast by usingisinstance():

  1. def f(o: object) -> None:
  2. if isinstance(o, int): # Mypy understands isinstance checks
  3. g(o + 1) # Okay; type of o is inferred as int here
  4. ...

Type inference in mypy is designed to work well in common cases, to bepredictable and to let the type checker give useful errormessages. More powerful type inference strategies often have complexand difficult-to-predict failure modes and could result in veryconfusing error messages. The tradeoff is that you as a programmersometimes have to give the type checker a little help.