微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

MyPy类型提示使用命名参数定义的函数,但可以使用** kwargs吗?

如何解决MyPy类型提示使用命名参数定义的函数,但可以使用** kwargs吗?

标题混乱的歉意:

假设我定义了一个带有许多参数函数

现在在我的代码后面,我使用字典将所有关键字args传递到test()中。

import argparse
from typing import Dict,Callable

def test(a: str,b: Dict[str,str],c: str,d: argparse.Namespace,e: Callable) -> None:
    if d.t:
        print(f"{a} to the {b['foo']} to the {c}!")
    else:
        print(f"{a} to the {b['foo']} to the {c} also,{e()}")

def hello() -> str:
    return "Hello"

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("-t",action="store_true",default=False)
    args = parser.parse_args()

    b = {'foo': 'bar'}
    info = {'b': b,"c": "foobar","d": args,"e": hello}
    test("foo",**info)

代码上运行MyPy时,出现以下错误

test.py:21: error: Argument 2 to "test" has incompatible type "**Dict[str,object]"; expected "Dict[str,str]"
test.py:21: error: Argument 2 to "test" has incompatible type "**Dict[str,object]"; expected "str"
test.py:21: error: Argument 2 to "test" has incompatible type "**Dict[str,object]"; expected "Namespace"
test.py:21: error: Argument 2 to "test" has incompatible type "**Dict[str,object]"; expected "Callable[...,Any]"
Found 4 errors in 1 file (checked 1 source file)

我为什么要得到这个?以及如何正确输入提示功能以允许此操作?

解决方法

example you had before类型检查的原因是因为plot_info的所有值都是str(同质),并且传递到函数中的所有关键字参数也都是str 。类型不匹配是不可能的,因此mypy报告成功。

在您的新示例中,info的异构类型不能单独编码成其类型。让我们看看运行reveal_type (info)时会发生什么:

note: Revealed type is 'builtins.dict[builtins.str*,builtins.object*]'

因此,我们看到mypy必须为该值选择一个齐整类型,并且与object一起使用。假设您通过了{{1},mypy是否可以保证对象字典满足bcde的单个类型约束}在它的眼皮底下?不,所以会出错。

要保留objectbcd的粒度类型,我们可以使用TypedDict,其目的是支持异构类型e s中的值:

Dict

并将class Info(TypedDict): b: Dict[str,str] c: str d: argparse.Namespace e: Callable 声明更改为:

info

这导致info: Info = {'b': b,"c": "foobar","d": args,"e": hello} 报告成功。

我们必须重复参数名称和类型。遗憾的是,Generate TypedDict from function's keyword arguments对此没有直接解决方法。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。