【问题标题】:How to convert Python string type annotation to proper type?如何将 Python 字符串类型注释转换为正确的类型?
【发布时间】: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


【解决方案1】:

你应该使用typing.get_type_hints

from __future__ import annotations
import dataclasses
from typing import get_type_hints

ObjectId = int


@dataclasses.dataclass
class Sample:
    id: ObjectId


def main() -> None:
    hints = get_type_hints(Sample)

    print(hints['id'])
    print(hints['id'] is int)


if __name__ == "__main__":
    main()
<class 'int'>
True

注意:我发现这种方法可能很慢,所以为了内存成本我缓存了结果:

from functools import cache
from typing import Any, Type, get_type_hints


@cache
def get_cached_type_hints(clazz: Type[Any]) -> dict[str, Type[Any]]:
    return get_type_hints(clazz)

【讨论】:

    猜你喜欢
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    • 2019-09-10
    • 1970-01-01
    • 2016-08-26
    • 2012-09-19
    • 1970-01-01
    相关资源
    最近更新 更多