Mypy 允许 `List[str]` 具有 `Tuple[str, List[str]]` 类型的值
Mypy allowing `List[str]` to have values of type `Tuple[str, List[str]]`
以下缩小的示例最初是在更改我的工作代码库时发现的。我有 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)
默认情况下 mypy
忽略 untyped function definitions。
这有助于逐步将类型注释引入现有代码库,而不必一次全部添加。
就我个人而言,对于新项目,我 运行 mypy
使用 --strict
选项来避免不小心留下未注释的函数和绕过类型检查。
以下缩小的示例最初是在更改我的工作代码库时发现的。我有 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)
默认情况下 mypy
忽略 untyped function definitions。
这有助于逐步将类型注释引入现有代码库,而不必一次全部添加。
就我个人而言,对于新项目,我 运行 mypy
使用 --strict
选项来避免不小心留下未注释的函数和绕过类型检查。