我在Python中使用类型注释时遇到了一个奇怪的问题。即使我注释了默认参数(即容器)或具有正确类型的容器变量,当容器为空或使用理解过滤出元素时,mypy
似乎也会感到困惑。这是我的示例:
from typing import Set, Tuple
_Path_t = Tuple[int]
# default argument example
def my_func(key: str, bases: Tuple[int] = ()):
pass
在上面运行mypy
会导致以下错误:
error: Incompatible default for argument "bases" \
(default has type "Tuple[]", argument has type "Tuple[int]")
理解时的另一个错误,可以用以下方法复制:
seqs: Set[_Path_t] = {tuple(range(n, n + 5)) for n in range(2, 3)}
while seqs:
seqs = [seq[:-1] for seq in seqs if seq[:-1]]
对于上面的分配行,mypy
发出错误:
error: Set comprehension has incompatible type Set[Tuple[int, ...]]; \
expected Set[Tuple[int]]
我的原始代码中不存在,可能是因为我没有使用范围。尽管while
循环中变量重新分配的错误是相同的:
error: Set comprehension has incompatible type Set[Tuple[]]; \
expected Set[Tuple[int]]
我想念什么?
[好吧,我想问题出在容器可能是空的这一事实。 This的答案将我引向了解决方案。在这两种情况下,我都需要使用Tuple[int, ...]
进行注释;本质上允许一个空的容器。