为标题混乱而道歉:
假设我定义了一个带有许多参数的函数。
现在,在以后的代码中,我使用字典将test()
所有关键字args传递给它。
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)
我为什么得到这个?以及如何正确键入提示函数以允许此操作?
您在进行类型检查之前的示例的原因是因为的所有值plot_info
都是str
(同质的),并且传递到函数中的所有关键字参数也都是str
。类型不匹配的可能性mypy
不大,因此报告成功。
在您的新示例中,info
不能将异构类型的单独编码为其类型。让我们看看运行时会发生什么:reveal_type
(info)
note: Revealed type is 'builtins.dict[builtins.str*, builtins.object*]'
因此,我们看到mypy
必须为该值选择一个同质类型,并且与一起使用object
。能mypy
保证对象满足您的个性化类型约束的字典b
,c
,d
,e
,因为你通过object
在其眼睛S' 不,所以它出错。
为了保持颗粒类型b
,c
,d
,e
,我们可以使用TypedDict
,这是为了支持在非均相类型的值Dict
S:
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}
这导致mypy
报告成功。
我们必须重复参数名称和类型。可悲的是,从函数的关键字参数生成TypedDict对此没有直接的解决方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句