一些功能,如 numpy.intersect1d 返回不同的类型(在这种情况下是ndarray或三个ndarray的元组),但编译器只能推断其中一个,所以如果我想这样做:
intersection: np.ndarray = np.intersect1d([1, 2, 3], [5, 6, 2])
它抛出一个类型警告:
Expected type 'ndarray', got 'Tuple[ndarray, ndarray, ndarray]' instead
我可以在其他语言中避免这种问题,比如Typescript,在那里我可以使用 as 关键字to assert the type (运行时不受影响)。我已经阅读了文档并看到了 cast 功能,但我想知道是否有 内联 解决方案或我缺少的东西。
as
根据the MyPy documentation ,有两种方法可以进行类型断言:
typing.cast(..., ...)
assert isinstance(..., ...)
int
list
List[int]
isinstance
由于文档中没有提到任何其他进行类型断言的方法,因此这些似乎是唯一的方法。