Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...