python中没有自动强制的任何类型

sqserrrh  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(430)

这个 Any -python中的类型是一种类型注解,指定值在运行时可以采用的类型是无约束的,不能静态确定。规则 Any 声明:
每种类型都与任何类型兼容,例如。

x: int = 8
y: Any = x

any与每种类型兼容,例如。

x: Any = 8
y: int = x

然而,第二条规则可能导致一些不健康的行为:

x: Any = 7
y: str = x

# Statically y has the type str, while in runtime it has the type int

这种行为在某些用例中可能有意义。但是,我试图表示外部数据块的类型(例如来自json api或pickle对象)。将返回类型注解为 Any 这是有意义的,因为您不知道静态数据将采用什么形式,然后执行什么操作 isinstance 检查和模式匹配以验证和提取数据的确切形状。但是,此强制规则使类型检查器不会验证这些检查是否正确,而是以静默方式转换 Any -类型,这通常不是运行时的正确行为。
目前我正在定义一个 Union -该类型在运行时可能具有的所有可能值的类型,但这不是一个可持续的解决方案,因为我发现自己不断地向 Union .
有吗 Any -就像python中的类型,它只有第一个强制规则,但没有第二个强制规则?

dffbzjpn

dffbzjpn1#

这个 object 类型是任何类型的有效基,但不是相反:

x: int = 8
y: object = x
x: object = 8
y: int = x     # error: Incompatible types in assignment (expression has type "object", variable has type "int")

在实践中,使用 :object 应该像 :Any . 然而,滥用 :object 不会像过去一样默默地过去 object 仅支持所有类型的最小操作:

x: int = 8
y: object = x

if isinstance(y, int):
    reveal_type(y)  # note: Revealed type is "builtins.int"
elif isinstance(y, list):
    reveal_type(y)  # note: Revealed type is "builtins.list[Any]"
else:
    reveal_type(y)  # note: Revealed type is "builtins.object"

相关问题