【发布时间】:2020-07-07 02:38:14
【问题描述】:
我在 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-loop 中的变量重新分配的错误是相同的:
error: Set comprehension has incompatible type Set[Tuple[]]; \
expected Set[Tuple[int]]
我错过了什么?
【问题讨论】:
标签: python-3.x containers type-hinting mypy