【发布时间】:2020-09-15 22:22:51
【问题描述】:
foo.py:
kwargs = {"a": 1, "b": "c"}
def consume(*, a: int, b: str) -> None:
pass
consume(**kwargs)
mypy foo.py:
error: Argument 1 to "consume" has incompatible type "**Dict[str, object]"; expected "int"
error: Argument 1 to "consume" has incompatible type "**Dict[str, object]"; expected "str"
这是因为object 是int 和str 的超类型,因此可以推断。如果我声明:
from typing import TypedDict
class KWArgs(TypedDict):
a: int
b: str
然后将kwargs 注释为KWArgs,mypy 校验通过。这实现了类型安全,但需要我在KWArgs 中复制consume 的关键字参数名称和类型。有没有办法在类型检查时从函数签名中生成这个TypedDict,这样我就可以最大限度地减少维护中的重复?
【问题讨论】:
-
我在这里发表评论,看看在最新版本的 mypy 中是否有任何更新?
标签: python type-hinting mypy