繁体   English   中英

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

[英]Generate TypedDict from function's keyword arguments

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注释为KWArgsmypy检查通过。 这实现了类型安全,但要求我要复制的关键字参数名称和类型consumeKWArgs 有没有办法在类型检查时从函数签名生成这个TypedDict ,这样我可以最大限度地减少维护中的重复?

据我所知,这个[1]没有直接的解决方法,但有另一种优雅的方式来实现这一点:

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

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__ ,这在检查时是未知的,并且定义一个装饰器来在运行时__annotations__转换类型错过了类型点检查。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM