下面的缩小示例最初是在更改我的工作代码库时发现的。我有行 x: List[str] = []
所以我希望 mypy 会强制执行这一点,但在这个例子中似乎没有。如果我想让 mypy 捕捉到这个,我应该做什么不同的事情?
from typing import List
x: List[str] = []
y = ["world"]
z = ["hello"]
def go(boop):
return f"{boop}!", y
x = list(map(go, z))
print(x)
# output:
# [('hello!', ['world'])]
$ mypy mypy_lists.py
Success: no issues found in 1 source file
$ python3 mypy_lists.py
[('hello!', ['world'])]
编辑:
就上下文而言,go
定义的 , y
部分是一个复制粘贴错误,我希望仅通过 x: List[str]
注释,但也许我必须更新 mypy 类型检查的内部模型,并且少信任它。
编辑2:
鉴于已接受的答案,我可以通过类型提示信任 mypy 的程度似乎与 mypy 的配置方式直接相关。这并不令人惊讶,但值得记住。
最佳答案
似乎向 go
函数添加类型注释会导致 mypy 正确识别问题:
$ mypy -c 'from typing import List, Tuple
x: List[str] = []
y = ["world"]
z = ["hello"]
def go(boop: str) -> Tuple[str, List[str]]:
return f"{boop}!", y
x = list(map(go, z))
print(x)'
<string>:10: error: Argument 1 to "map" has incompatible type "Callable[[Any], Tuple[str, List[str]]]"; expected "Callable[[str], str]"
Found 1 error in 1 file (checked 1 source file)
关于python - Mypy 允许 `List[str]` 具有 `Tuple[str, List[str]]` 类型的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69618160/