如何解决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)
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
是否可以保证对象字典满足b
,c
,d
,e
的单个类型约束}在它的眼皮底下?不,所以会出错。
要保留object
,b
,c
,d
的粒度类型,我们可以使用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 举报,一经查实,本站将立刻删除。