【发布时间】:2021-09-07 15:30:06
【问题描述】:
一些 Python 类型注解可以指定为字符串,例如允许递归。但是,我需要为运行时评估找到正确的类型。如果我 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()
如何将基于字符串的类型注释转换为正确的类类型?
【问题讨论】:
标签: python python-typing python-3.10