Python 键入:从 TypedDict 定义中检索所需的键
Python typing: Retrieve required keys from TypedDict definition
在 Python3.10 中,我有一个 typing.TypedDict
定义并希望以编程方式检索需要哪些键。如何检查类型定义以获得所需的键?
以 PEP-655 into account, there are different scenarios: The whole TypedDict
could have total=False
or total=True
, and individual fields could be marked as either Required
or NotRequired
. And there could also be the edge case 为例,其中一个 TypedDict
继承自另一个,其中一个具有 total=False
,另一个具有 total=True
。为了处理这种边缘情况,Python 在 TypedDict
上引入了 __required_keys__
属性。这是我们要看的:
from typing import Any, _TypedDictMeta
def required_keys(type_: _TypedDictMeta) -> frozenset[str]:
return type_.__required_keys__
在 Python3.10 中,我有一个 typing.TypedDict
定义并希望以编程方式检索需要哪些键。如何检查类型定义以获得所需的键?
以 PEP-655 into account, there are different scenarios: The whole TypedDict
could have total=False
or total=True
, and individual fields could be marked as either Required
or NotRequired
. And there could also be the edge case 为例,其中一个 TypedDict
继承自另一个,其中一个具有 total=False
,另一个具有 total=True
。为了处理这种边缘情况,Python 在 TypedDict
上引入了 __required_keys__
属性。这是我们要看的:
from typing import Any, _TypedDictMeta
def required_keys(type_: _TypedDictMeta) -> frozenset[str]:
return type_.__required_keys__