Casts and type assertions

Mypy supports type casts that are usually used to coerce a staticallytyped value to a subtype. Unlike languages such as Java or C#,however, mypy casts are only used as hints for the type checker, and theydon’t perform a runtime type check. Use the function cast() to perform acast:

  1. from typing import cast, List
  2.  
  3. o: object = [1]
  4. x = cast(List[int], o) # OK
  5. y = cast(List[str], o) # OK (cast performs no actual runtime check)

To support runtime checking of casts such as the above, we’d have to checkthe types of all list items, which would be very inefficient for large lists.Casts are used to silence spurioustype checker warnings and give the type checker a little help when it can’tquite understand what is going on.

Note

You can use an assertion if you want to perform an actual runtime check:

  1. def foo(o: object) -> None:
  2. print(o + 5) # Error: can't add 'object' and 'int'
  3. assert isinstance(o, int)
  4. print(o + 5) # OK: type of 'o' is 'int' here

You don’t need a cast for expressions with type Any, or whenassigning to a variable with type Any, as was explained earlier.You can also use Any as the cast target type – this lets you performany operations on the result. For example:

  1. from typing import cast, Any
  2.  
  3. x = 1
  4. x.whatever() # Type check error
  5. y = cast(Any, x)
  6. y.whatever() # Type check OK (runtime error)