MyPy 中的类型断言 [英] Type assertion in MyPy

查看:48
本文介绍了MyPy 中的类型断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一些函数,如 numpy.intersect1d 返回不同的类型(在这种情况下是一个 ndarray 或三个 ndarray 的元组)但编译器只能推断其中一个,所以如果我想制作:

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])

它抛出一个类型警告:

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

我可以在其他语言(如 Typescript)中避免此类问题,我可以使用 as 关键字来断言类型(对运行时没有影响).我已经阅读了文档并看到了 cast 函数,但我想知道是否有任何内联解决方案或我缺少的东西.

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.

推荐答案

根据 MyPy 文档,有两种方法可以进行类型断言:

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

  • 作为内联表达式,您可以使用 cast 函数.文档说这是通常"已完成从超类型转换为子类型的操作,但并不表示您不能在其他情况下使用它.
  • 作为声明,您可以使用 assert isinstance(..., ...),但这仅适用于像 int 这样的具体类型list 在运行时表示,而不是像 List[int] 这样不能被 isinstance 检查的更复杂的类型.
  • 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.

这篇关于MyPy 中的类型断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆