mypy:如何解决这个元组混乱

时间:2017-06-27 06:03:46

标签: python mypy

Python 3.6对此元组示例没有任何问题:

# tpl is a tuple. Each entry consists of a tuple with two entries. The first
# of those is a tuple of two strings. The second one is a tuple of tuples with
# three strings.

tpl = (
    (('a', 'b'), (('1', '2', '3'), ('4', '5', '6'))),
    (('c', 'd'), (('7', '8', '9'),)),
    )

for first_tuple, second_tuple in tpl:
    str1, str2 = first_tuple
    print(str1, str2)
    for str1, str2, str3 in second_tuple:
        print('   ', str1, str2, str3)
    print()

输出:

a b
    1 2 3
    4 5 6

c d
    7 8 9

但mypy 0.511似乎感到困惑并报告错误:

ttpl.py:13: error: Iterable expected
ttpl.py:13: error: "object" has no attribute "__iter__"; maybe "__str__"?

我能做些什么来帮助mypy了解正在发生的事情?

2 个答案:

答案 0 :(得分:2)

mypy默认将元组视为元组,而不是序列(object)。当迭代具有不兼容类型的元组时,变量的类型被确定为for x in ((1,), (2, 3)): reveal_type(x) for y in x: pass

from typing import Tuple

tpl: Tuple[Tuple[Tuple[str, str], Tuple[Tuple[str, str, str], ...]], ...] = (
    (('a', 'b'), (('1', '2', '3'), ('4', '5', '6'))),
    (('c', 'd'), (('7', '8', '9'),)),
)

您可以提供适当的,非常漂亮的类型提示:

{{1}}

表示实际数据格式的类型别名可能会有所帮助。

答案 1 :(得分:0)

虽然Ryan给出了python 3.6的正确答案,同时也让我了解了正在发生的事情,我想指出两种可能的选择:

如果您仍然需要使用没有PEP 526的python版本(变量注释的语法),您可以这样做:

from typing import Tuple, Iterable

TypeOfData = Iterable[
    Tuple[
        Tuple[str, str],
        Iterable[Tuple[str, str, str]]
        ]
    ]

tpl = (
    (('a', 'b'), (('1', '2', '3'), ('4', '5', '6'))),
    (('c', 'd'), (('7', '8', '9'),)),
    ) # type: TypeOfData

for first_tuple, second_tuple in tpl:
    str1, str2 = first_tuple
    print(str1, str2)
    for str1, str2, str3 in second_tuple:
        print('   ', str1, str2, str3)
    print()][1]

如果您只想让mypy报告错误,也可以这样做:

tpl = (
    (('a', 'b'), (('1', '2', '3'), ('4', '5', '6'))),
    (('c', 'd'), (('7', '8', '9'),)),
    )

for first_tuple, second_tuple in tpl:
    str1, str2 = first_tuple
    print(str1, str2)
    for str1, str2, str3 in second_tuple: # type: ignore
        print('   ', str1, str2, str3)
    print()