【问题标题】:Incompatible type when using containers [duplicate]使用容器时不兼容的类型[重复]
【发布时间】: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


    【解决方案1】:

    好的,我想问题源于容器可能是空的。 This 回答让我找到了解决方案。在这两种情况下,我都需要使用Tuple[int, ...] 进行注释;本质上允许一个空容器。

    【讨论】:

      猜你喜欢
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多