通过阅读mypy
问题,似乎调用dict.update()
并提供TypedDict
不是类型安全的。这对我来说没有意义
我的问题是(特别是第二期,链接如下):
TypedDict
在运行时是一个dict
,为什么mypy
抱怨不能将一个TypedDict
传递到dict.update
,说它需要一个Mapping
?
dict
就像说Dict[Any, Any]
,那么为什么不添加一个TypedDict
作为dict值呢李>dict.update(SomeTypedDict)
不是类型安全的李>这方面有两个例子,见mypy
期:
This is a pretty subtle issue. The update call is arguably not type safe.
Since TypedDict objects use structural subtyping, there could be additional items not visible through the type
Foo
, with arbitrary value types. ThusMapping[str, object]
is correct (though it is unintuitive).
示例代码来自python/mypy #9086
from typing import TypedDict
class Foo(TypedDict):
baz: int
foo: Foo = {"baz": 9000}
# spam is a regular dict, yet mypy errors out when trying to add a TypedDict
# to it. This doesn't make sense to me, when a regular dict should be like
# saying equal Dict[Any, Any]
spam = {"ham": {"eggs": 5}}
spam["ham"].update(foo) # error: Argument 1 to "update" of "dict" has
# incompatible type "Foo"; expected "Mapping[str, int]" [arg-type]
PEP 589说:
例如:
更新:让我们考虑你的样本
相关问题 更多 >
编程相关推荐