我想从未绑定的TypedDict
子类中获取密钥。
正确的方法是什么?
下面我有一个黑客方法,我想知道是否有更标准的方法。
当前方法
我在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'])
这确实有效,但我想知道,有没有更好/更标准的方法?
版本
python==3.6.5
typing-extensions==3.7.4.2
代码文档明确指出(参考示例派生类Point2D
(:
类型信息可以通过
Point2D.__annotations__
字典以及冻结集Point2D.__required_keys__
和Point2D.__optional_keys__
来访问。
因此,如果模块代码这样说,则没有理由寻找另一种方法。
请注意,您的方法仅打印字典键的名称。您只需访问完整的字典即可获取名称和类型:
print(SomeTypedDict.__annotations__)
这将使您返回所有信息:
{'key1': <class 'str'>, 'key2': <class 'int'>}
您还可以声明如下所示的静态方法:
from typing import TypedDict
class StockPrice(TypedDict):
symbol: str
year: int
month: int
day: int
o: int
h: int
l: int
c: int
v: int | None
@staticmethod# type: ignore
def keys():
return StockPrice.__dict__['__annotations__'].keys()
StockPrice.keys()
#dict_keys(['symbol', 'year', 'month', 'day', 'o', 'h', 'l', 'c', 'v'])
您可以使用get_type_hints
函数。
from typing import TypedDict, get_type_hints
class StackParams(TypedDict):
UnsignedAuthorizerName: str
UnsignedAuthorizerStatus: bool
TableName: str
SignedAuthorizerName: str
SignedAuthorizerStatus: bool
SignedAuthorizerTokenKeyName: str
get_type_hints(StackParams)
# {'UnsignedAuthorizerName': str, 'UnsignedAuthorizerStatus': bool, 'TableName': str, 'SignedAuthorizerName': str, 'SignedAuthorizerStatus': bool, 'SignedAuthorizerTokenKeyName': str}