python - Python中的任何类型,没有自动强制
问题描述
Python 中的Any
-type是一个类型注释,指定一个值在运行时可以采用的类型不受约束,不能静态确定。规则Any
规定:
- 每种类型都与 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 对象)。将返回类型注释为 anAny
是有意义的,因为您静态地不知道数据将采用什么形式,然后进行isinstance
检查和模式匹配以验证和提取数据的确切形状。然而,这个强制规则使得类型检查器不会验证这些检查是否正确,而是默默地将Any
-types 转换为它推断的任何内容,这在运行时通常不是正确的行为。
目前,我正在定义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"
推荐阅读
- reactjs - 使用 React 和 @googlemaps/js-api-loader 未显示 Google 地图标记
- ios - 我们可以集成支付网关还是我必须使用 inApp-purchase
- docker - Windows docker:参考格式无效
- python - 如何将一列拆分为不同大小的不同部分?
- javascript - MEAN-如何找到数组的长度?
- google-cloud-run - 使用云运行启动spring boot时如何解决超时
- laravel - 最佳实践标准 - Laravel Eloquent/Model 的 SQL 查询
- sql - 将数据库列转换为 SQL 查询
- identityserver4 - 保护 blazor webassembly 托管应用程序
- python - 创建年、月、日文件夹 Python