Python 从未绑定的 TypedDict 获取键
Python get keys from unbound TypedDict
我想从未绑定的 TypedDict
子类中获取密钥。
这样做的正确方法是什么?
下面我有一个hacky方法,我想知道是否有更标准的方法。
当前方法
我在 TypedDict
子类上使用了 inspect.getmembers
,并看到 __annotations__
属性包含键 + 类型注释的映射。从那里,我使用 .keys()
访问所有密钥。
from typing_extensions import TypedDict
class SomeTypedDict(TypedDict):
key1: str
key2: int
print(SomeTypedDict.__annotations__.keys())
打印:dict_keys(['key1', 'key2'])
这确实有效,但我想知道,是否有 better/more 标准方法?
版本
python==3.6.5
typing-extensions==3.7.4.2
code documentation明确指出(指派生classPoint2D
的样本):
The type info can be accessed via the Point2D.__annotations__
dict, and the Point2D.__required_keys__
and Point2D.__optional_keys__
frozensets.
所以如果模块代码这样说,就没有理由寻找其他方法。
请注意,您的方法只打印了字典键的名称。您只需访问完整词典即可获取名称和类型:
print(SomeTypedDict.__annotations__)
这将使您返回所有信息:
{'key1': <class 'str'>, 'key2': <class 'int'>}
我想从未绑定的 TypedDict
子类中获取密钥。
这样做的正确方法是什么?
下面我有一个hacky方法,我想知道是否有更标准的方法。
当前方法
我在 TypedDict
子类上使用了 inspect.getmembers
,并看到 __annotations__
属性包含键 + 类型注释的映射。从那里,我使用 .keys()
访问所有密钥。
from typing_extensions import TypedDict
class SomeTypedDict(TypedDict):
key1: str
key2: int
print(SomeTypedDict.__annotations__.keys())
打印:dict_keys(['key1', 'key2'])
这确实有效,但我想知道,是否有 better/more 标准方法?
版本
python==3.6.5
typing-extensions==3.7.4.2
code documentation明确指出(指派生classPoint2D
的样本):
The type info can be accessed via the
Point2D.__annotations__
dict, and thePoint2D.__required_keys__
andPoint2D.__optional_keys__
frozensets.
所以如果模块代码这样说,就没有理由寻找其他方法。
请注意,您的方法只打印了字典键的名称。您只需访问完整词典即可获取名称和类型:
print(SomeTypedDict.__annotations__)
这将使您返回所有信息:
{'key1': <class 'str'>, 'key2': <class 'int'>}