Python 从未绑定的 TypedDict 中获取键

Int*_*rer 2 python dictionary type-hinting python-typing

我想从未绑定的TypedDict子类中获取密钥。

这样做的正确方法是什么?

下面我有一个hacky方法,我想知道是否有更标准的方法。


当前方法

inspect.getmembersTypedDict子类上使用,并看到__annotations__属性包含键 + 类型注释的映射。从那里,我.keys()用来访问所有密钥。

from typing_extensions import TypedDict


class SomeTypedDict(TypedDict):

    key1: str
    key2: int


print(SomeTypedDict.__annotations__.keys())
Run Code Online (Sandbox Code Playgroud)

印刷: dict_keys(['key1', 'key2'])

这确实有效,但我想知道,有没有更好/更标准的方法?


版本

python==3.6.5
typing-extensions==3.7.4.2
Run Code Online (Sandbox Code Playgroud)

Ami*_*ron 5

代码文档明确规定(指样品派生类Point2D):

类型信息可以通过Point2D.__annotations__dict、Point2D.__required_keys__Point2D.__optional_keys__frozensets 访问。

因此,如果模块代码说明了这一点,则没有理由寻找其他方法。

请注意,您的方法仅打印字典键的名称。您只需访问完整字典即可获取名称和类型:

print(SomeTypedDict.__annotations__)
Run Code Online (Sandbox Code Playgroud)

这将使您返回所有信息:

{'key1': <class 'str'>, 'key2': <class 'int'>}
Run Code Online (Sandbox Code Playgroud)