Type assertion in MyPy

Some functions like numpy.intersect1d return differents types (in this case an ndarray or a tuple of three ndarrays) but the compiler can only infer one of them, so if I like to make:

intersection: np.ndarray = np.intersect1d([1, 2, 3], [5, 6, 2])

It throws a type warning:

Expected type 'ndarray', got 'Tuple[ndarray, ndarray, ndarray]' instead

I could avoid this kind of problems in other languages like Typescript where I could use the as keyword to assert the type (without impact in runtime). I've read the documentation and saw the cast function, but I'd to know if there is any inline solution or something I'm missing.


Solution 1:

According to the MyPy documentation, there are two ways to do type assertions:

  • As an inline expression, you can use the cast function. The docs say this is "usually" done to cast from a supertype to a subtype, but doesn't say you can't use it in other cases.
  • As a statement, you can use assert isinstance(..., ...), but this will only work with concrete types like int or list which are represented at runtime, not more complex types like List[int] which can't be checked by isinstance.

Since the documentation doesn't mention any other ways to do type assertions, it seems like these are the only ways.