从函数的关键字参数生成TypedDict

时间:2020-09-15 22:22:51

标签: python type-hinting mypy

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"

这是因为objectintstr的超类型,因此可以推断出来。如果我声明:

from typing import TypedDict

class KWArgs(TypedDict):
    a: int
    b: str

,然后将kwargs注释为KWArgs,则mypy检查通过。这样可以实现类型安全,但是需要我在consume中为KWArgs复制关键字参数名称和类型。有没有一种方法可以在类型检查时从函数签名生成此TypedDict,以便可以最大程度地减少维护方面的重复?

1 个答案:

答案 0 :(得分:2)

据我所知,对此 [1] 并没有直接的解决方法,但是还有另一种优雅的方法可以实现这一目标:

我们可以利用typing s NamedTuple创建一个保存参数的对象:

ConsumeContext = NamedTuple('ConsumeContext', [('a', int), ('b', str)])

现在,我们定义consume方法来接受它作为参数:

def consume(*, consume_context : ConsumeContext) -> None:
    print(f'a : {consume_context.a} , b : {consume_context.b}')

整个代码为:

from typing import NamedTuple

ConsumeContext = NamedTuple('ConsumeContext', [('a', int), ('b', str)])

def consume(*, consume_context : ConsumeContext) -> None:
    print(f'a : {consume_context.a} , b : {consume_context.b}')

ctx = ConsumeContext(a=1, b='sabich')

consume(consume_context=ctx)

运行mypy将产生:

Success: no issues found in 1 source file

它将认识到ab是参数,并予以批准。

运行代码将输出:

a : 1 , b : sabich

但是,如果我们将b更改为非字符串,mypy将抱怨:

foo.py:9: error: Argument "b" to "ConsumeContext" has incompatible type "int"; expected "str"
Found 1 error in 1 file (checked 1 source file)

通过这种方式,我们通过定义方法的参数和类型来实现方法的类型检查。

[1]因为如果基于另一个定义TypedDict或函数签名,则需要知道另一个__annotations__(在检查时未知),并进行定义在运行时强制转换类型的装饰器错过了类型检查的要点。