Complex type tests
Mypy can usually infer the types correctly when using isinstance
type tests, but for other kinds of checks you may need to add anexplicit type cast:
- def f(o: object) -> None:
- if type(o) is int:
- o = cast(int, o)
- g(o + 1) # This would be an error without the cast
- ...
- else:
- ...
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()
:
- def f(o: object) -> None:
- if isinstance(o, int): # Mypy understands isinstance checks
- g(o + 1) # Okay; type of o is inferred as int here
- ...
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.