11

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.

2
  • mypy.readthedocs.io/en/stable/casts.html - since the docs don't mention any alternative way to do type assertions, I would assume there isn't one. Commented Sep 10, 2020 at 12:31
  • Thanks for your comment! If you like make an answer and i'll mark as the accepted one Commented Sep 10, 2020 at 18:45

1 Answer 1

19

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

  • As an inline expression, you can use the typing.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.

Sign up to request clarification or add additional context in comments.

2 Comments

And there can't be a better way, because List[int] is not a class. List is a class and you can check if its elements are int, but there is nothing about a list-object that tells you it can only hold a certain type of object. In Java they call this 'type erasure', I don't know if python uses that term too, but the concept is the same. The generic parameter does not exist at runtime.
A runtime-type-checking-library like beartype will try to assert List[int] by checking the first element (performant default) or all elements. For lists this works, for an Iterable[int] even that approach would be impossible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.