一些 Python 类型注释可以指定为字符串,例如允许递归。但是,我需要为运行时评估找到正确的类型。如果 I 也使用字符串from __future__ import annotations
,它是 Python 3.10 中的默认值(如果我没看错的话)。鉴于这些字符串,我需要获得正确的类型。
例如,在这段代码中,字段类型是<class 'int'>
如果我不从未来导入,但"ObjectId"
如果我这样做。... is int
更重要的是,仅当我不进行导入时,检查才为真。
# Toggle the comment on the next line
# from __future__ import annotations
import dataclasses
ObjectId = int
@dataclasses.dataclass
class Sample:
id: ObjectId
def main() -> None:
fields = dataclasses.fields(Sample)
print(fields[0].type)
print(fields[0].type is int)
main()
如何将基于字符串的类型注释转换为正确的类类型?