使用容器时不兼容的类型[重复]

问题描述 投票:1回答:1

我在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]]

我想念什么?

python-3.x containers type-hinting mypy
1个回答
0
投票

[好吧,我想问题出在容器可能是空的这一事实。 This的答案将我引向了解决方案。在这两种情况下,我都需要使用Tuple[int, ...]进行注释;本质上允许一个空的容器。

© www.soinside.com 2019 - 2024. All rights reserved.