foo.py:
kwargs = {"a": 1, "b": "c"}
def consume(*, a: int, b: str) -> None:
pass
consume(**kwargs)
Run Code Online (Sandbox Code Playgroud)
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"
Run Code Online (Sandbox Code Playgroud)
这是因为object是intand的超类型,str因此被推断出来。如果我声明:
from typing import TypedDict
class KWArgs(TypedDict):
a: int
b: str
Run Code Online (Sandbox Code Playgroud)
然后注释kwargs为KWArgs,mypy检查通过。这实现了类型安全,但需要我复制consumein的关键字参数名称和类型KWArgs。有没有办法TypedDict在类型检查时从函数签名中生成它,以便我可以最大限度地减少维护中的重复?