Python 中的任意类型,无自动强制转换

Any-type in Python without automatic coercion

Python 中的 Any-type 是一个类型注释,指定值在运行时可以采用的类型是不受约束的,不能静态确定。 Any 的规则规定:

x: int = 8
y: Any = x
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 对象)。将 return 类型注释为 Any 是有意义的,因为您静态地不知道数据将采用什么形式,然后进行 isinstance 检查和模式匹配以验证和提取确切的形状的数据。然而,这种强制规则使得类型检查器不会验证这些检查是否正确,而是默默地将 Any 类型转换为它推断的任何类型,这在运行时通常不是正确的行为。

目前我正在定义一个 Union 类型,该类型在运行时可能具有所有可能的值,但这不是一个可持续的解决方案,因为我发现自己不断地向 Union.

Python中是否有类似Any的类型只有第一个强制转换规则而没有第二个?

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"