python 类型注释不会影响静态类型检查器

问题描述 投票:0回答:1

我想在运行时使用 python (3.12) 类型注释来达到我自己的目的,与变量类型无关。该语法非常方便向变量添加元数据。

所以我想用一种不会影响可能发生的任何静态类型分析的类型进行注释。注释 PEP 参考了像我这样的用途(即使用注释进行静态类型分析以外的事情),特别是

Annotated
接近我的需要。问题是我想跳过
Annotated
的第一个参数,因为我实际上不想将类型与对象关联 - 我只想关联元数据。

是否有一种类型(或者可以构建一种类型)不会改变静态类型分析?我知道

Any
是一个合理的选择,但这会改变静态类型分析。例如,pyright 将没有类型注释的变量分配为类型
Unknown
(而不是
Any
)。

python type-hinting python-typing pyright
1个回答
0
投票
from typing import Annotated, Any

# Annotate a variable with metadata using Annotated with Any
my_variable: Annotated[Any, "metadata_key"] = "value"

# Access the metadata associated with the variable
metadata_value = my_variable.__annotations__["metadata_key"]
print(metadata_value)  # Output: "value"
© www.soinside.com 2019 - 2024. All rights reserved.