我对我的身体有问题。
我有这样的代码:
func(arg1, arg2, arg3=0.0, arg4=0.0)
# type: (float, float, float, float) -> float
# do something and return float.
dict_with_other_arguments = {arg3: 0.5, arg4: 1.4}
a = func(arg1, arg2, **dict_with_other_arguments)问题是,mypy不检查字典中的类型,相反,我得到了如下错误:
错误:参数3到"func“有不兼容的类型"**Dictstr,float";预期的"float”
有什么想法吗?如何在不改变代码的情况下解决这个问题?
发布于 2018-12-12 01:57:05
Mypy在标记函数调用时是正确的。以下代码说明了原因:
def func(str_arg='x', float_arg=3.0):
# type: (str, float) -> None
print(str_arg, float_arg)
kwargs1 = {'float_arg': 8.0}
kwargs2 = {'str_arg': 13.0} # whoops
func(float_arg=5.0) # prints "x 5.0" -- good
func(**kwargs1) # prints "x 13.0" -- good but flagged by Mypy
func(**kwargs2) # prints "13.0 3.0" -- bad在本例中,kwargs1和kwargs2都是Dict[str, float]类型。类型检查器不考虑键的内容,只考虑它们的类型,因此对func的第二次和第三次调用看起来与Mypy相同。它们要么都是错误,要么都是可接受的,而且它们都不能被接受,因为第三个调用违反了类型系统。
类型检查器可以确保在dict中没有传递不正确类型的唯一方法是,所有未显式传递的参数都共享dict值的类型。但是,请注意,mypy不会保护您免受在dict中重新指定关键字参数所导致的错误:
# This works fine:
func('x', **kwargs1)
# This is technically type safe and accepted by mypy, but at runtime raises
# `TypeError: func() got multiple values for argument 'str_arg'`:
func('x', **kwargs2)这里有一些关于这个问题的进一步讨论:https://github.com/python/mypy/issues/1969
https://stackoverflow.com/questions/47632128
复制相似问题