这取决于。
PEP-589,规范TypedDict, https://peps.python.org/pep-0589/明确禁止额外的键:
TypedDict 中包含额外的键对象构造也应该被抓住。在此示例中,导演键未在 Movie 中定义,并且预计会从类型检查器中生成错误:
m: Movie = dict(
name='Alien',
year=1979,
director='Ridley Scott') # error: Unexpected key 'director'
[我强调的]
类型检查器 mypy、pyre、pyright 根据规范实现这一点。
然而,有可能接受带有额外键的值。这是因为 TypedDicts 的子类型是允许的,并且子类型可能实现额外的键。 PEP-589 仅禁止在对象构造中使用额外的键,即在文字赋值中。由于任何符合子类型的值始终被视为符合父类型,并且可以从子类型向上转换为父类型,因此可以通过子类型引入额外的键:
from typing import TypedDict
class Movie(TypedDict):
name: str
year: int
class MovieWithDirector(Movie):
director: str
# This is illegal:
movie: Movie = {
'name': 'Ash is purest white',
'year': 2018,
'director': 'Jia Zhangke',
}
# This is legal:
movie_with_director: MovieWithDirector = {
'name': 'Ash is purest white',
'year': 2018,
'director': 'Jia Zhangke',
}
# This is legal, MovieWithDirector is a subtype of Movie
movie: Movie = movie_with_director
在上面的例子中,我们看到有时可以认为相同的值符合Movie
通过打字系统,有时不是。
作为子类型化的结果,将参数键入为某个 TypedDict 并不能防止额外的键,因为它们可能是通过子类型引入的。
如果您的代码对额外键的存在很敏感(例如,如果它使用param.keys()
, param.values()
or len(param)
on the TypedDict
范围param
),当存在额外的密钥时,这可能会导致问题。此问题的解决方案是处理参数上实际存在额外键的特殊情况,或者使代码对额外键不敏感。
如果您想测试您的代码是否对额外的键具有鲁棒性,则不能简单地在测试值中添加键:
def some_movie_function(movie: Movie):
# ...
def test_some_movie_function():
# this will not be accepted by the type checker:
result = some_movie_function({
'name': 'Ash is purest white',
'year': 2018,
'director': 'Jia Zhangke',
'genre': 'drama',
})
解决方法是使类型检查器忽略该行或为您的测试创建一个子类型,仅为您的测试引入额外的键:
class ExtendedMovie(Movie):
director: str
genre: str
def test_some_movie_function():
extended_movie: ExtendedMovie = {
'name': 'Ash is purest white',
'year': 2018,
'director': 'Jia Zhangke',
'genre': 'drama',
}
result = some_movie_function(test_some_movie_function)
# run assertions against result
}