Python打字:打字件是否允许其他 /额外的密钥?
typing.typeddict
允许额外的密钥吗?如果typechecker的键在TypedDict的定义上不存在?
Does typing.TypedDict
allow extra keys? Does a value pass the typechecker, if it has keys which are not present on the definition of the TypedDict?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您知道可选键,则可以使用
total=False
:If you know the optionals keys, you can use
total=False
:这取决于。
PEP-589,
TypedDict
规范, 明确禁止额外的键:[我强调]
类型检查器
mypy
、pyre
和pyright
根据规范实现这一点。然而,有可能接受带有额外键的值。这是因为 TypedDicts 的子类型是允许的,并且子类型可能实现额外的键。 PEP-589 仅禁止在对象构造中(即文字赋值中)使用额外的键。由于任何符合子类型的值总是被认为符合父类型,并且可以从子类型向上转换为父类型,因此可以通过子类型引入额外的键:
在上面的示例中,我们看到相同的值有时打字系统会认为它符合
Movie
,有时则不然。作为子类型化的结果,将参数键入为某个 TypedDict 并不能防止额外的键,因为它们可能是通过子类型引入的。
如果您的代码对额外键的存在很敏感(例如,如果它使用
param.keys()
、param.values()
或len(param)
在TypedDict
参数param
上),当存在额外的键时,这可能会导致问题。此问题的解决方案是要么处理参数上实际存在额外键的特殊情况,要么使代码对额外键不敏感。如果您想测试您的代码对于额外键的鲁棒性,则不能简单地在测试值中添加键:
解决方法是使类型检查器忽略该行或为您的测试创建一个子类型,仅引入额外键为了你的测试:
It depends.
PEP-589, the specification of
TypedDict
, explicitely forbids extra keys:[emphasis by me]
The typecheckers
mypy
,pyre
, andpyright
implement this according to the specification.However, it is possible that a value with extra keys is accepted. This is because subtyping of TypedDicts is allowed, and the subtype might implement the extra key. PEP-589 only forbids extra keys in object construction, i.e. in literal assignment. As any value that complies with a subtype is always deemed to comply with the parent type and can be upcasted from the subtype to the parent type, an extra key can be introduced through a subtype:
In the example above, we see that the same value can sometimes be considered complying with
Movie
by the typing system, and sometimes not.As a consequence of subtyping, typing a parameter as a certain TypedDict is not a safeguard against extra keys, because they could have been introduced through a subtype.
If your code is sensitive with regard to the presence of extra keys (for instance, if it makes use of
param.keys()
,param.values()
orlen(param)
on theTypedDict
parameterparam
), this could lead to problems when extra keys are present. A solution to this problem is to either handle the exceptional case that extra keys are actually present on the parameter or to make your code insensitive against extra keys.If you want to test that your code is robust against extra keys, you cannot simply add a key in the test value:
Workarounds are to either make the type checkers ignore the line or to create a subtype for your test, introducing the extra keys only for your test:
Python TypedDict 尚不支持额外的项目,可能会在 python3.13 中支持。
请参阅 PEP728
Python TypedDict does not support extra items yet and may be supported in python3.13 .
See in PEP728