如何为Python类型检查编写arrowing_cast

时间:2020-05-01 16:36:40

标签: python-3.x mypy

我正在寻找一种使用typing.cast之类的语法创建函数的方法,但其行为更像是类型提示。

cast模块中的typing调用有效地保证传递的值将是建议的类型。一些明智的强制转换可能很有用,但是它们有些令人担忧,因为即使它们可以证明声明是错误的,它们也会阻止MyPy标记任何内容。

a = cast(int, untyped_foreign_library.get_width()) # Useful
b = cast(int, "hello") # Trouble

一种不错的替代方法是提供类型提示:

a : int = untyped_foreign_library.get_width() # Equally useful
b : int = "hello" # MyPy notices the mistake because hints can only narrow the options.

这是更好的选择,但语法有点不合理。尤其是当用于提示返回表达式时,它需要多余的一行。

def foo() -> int:
    res: int = untyped_foreign_library.get_width()
    return res

我想要的是拼写相同的安全级别

def foo() -> int:
    return narrow_cast(int, untyped_foreign_library.get_width())

def bar() -> int:
    return narrow_cast(int, "hello") # MyPy should complain that this is not a legal cast.

就我自己的尝试而言:

我可以(大致来说,正常工作需要使用MyPy特殊大小写)将cast的当前行为复制为

T = TypeVar("T")

def my_cast(target_type: Type[T], value: Any) -> T:
    return value

但是,这会忽略value的类型。粗略地讲,我需要一种表达value必须是第二个TypeVar的方式,该第二个TypeVar必须始终是T的超类型。但是,不支持TypeVar之间的绑定关系。

0 个答案:

没有答案