MyPy 中的类型断言
Type assertion in MyPy
有些函数像 numpy.intersect1d return 不同的类型(在本例中是一个 ndarray 或三个 ndarray 的元组)但是编译器只能推断其中一个,所以如果我想做:
intersection: np.ndarray = np.intersect1d([1, 2, 3], [5, 6, 2])
它抛出类型警告:
Expected type 'ndarray', got 'Tuple[ndarray, ndarray, ndarray]' instead
我可以在 Typescript 等其他语言中避免此类问题,我可以在 as
关键字中使用 assert the type (without impact in runtime). I've read the documentation and saw the cast 函数,但我想知道是否有任何 inline 解决方案或我遗漏的东西。
根据MyPy documentation,有两种方法可以进行类型断言:
- 作为内联表达式,您可以使用
cast
函数。文档说这“通常”用于从超类型转换为子类型,但并没有说您不能在其他情况下使用它。
- 作为声明,您可以使用
assert isinstance(..., ...)
,但这只适用于在运行时表示的具体类型,例如 int
或 list
,而不适用于更复杂的类型,例如 List[int]
无法通过 isinstance
. 检查
由于文档没有提到任何其他方法来进行类型断言,似乎这些是唯一的方法。
有些函数像 numpy.intersect1d return 不同的类型(在本例中是一个 ndarray 或三个 ndarray 的元组)但是编译器只能推断其中一个,所以如果我想做:
intersection: np.ndarray = np.intersect1d([1, 2, 3], [5, 6, 2])
它抛出类型警告:
Expected type 'ndarray', got 'Tuple[ndarray, ndarray, ndarray]' instead
我可以在 Typescript 等其他语言中避免此类问题,我可以在 as
关键字中使用 assert the type (without impact in runtime). I've read the documentation and saw the cast 函数,但我想知道是否有任何 inline 解决方案或我遗漏的东西。
根据MyPy documentation,有两种方法可以进行类型断言:
- 作为内联表达式,您可以使用
cast
函数。文档说这“通常”用于从超类型转换为子类型,但并没有说您不能在其他情况下使用它。 - 作为声明,您可以使用
assert isinstance(..., ...)
,但这只适用于在运行时表示的具体类型,例如int
或list
,而不适用于更复杂的类型,例如List[int]
无法通过isinstance
. 检查
由于文档没有提到任何其他方法来进行类型断言,似乎这些是唯一的方法。