Python mypy:如何解决元组混淆
Python 3.6对这个元组示例没有问题:Python mypy:如何解决元组混淆,python,mypy,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',
# 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了解发生了什么?mypy默认将元组视为元组,而不是序列(
Tuple[T,…]
)。当您在具有不兼容类型的元组上迭代时,变量的类型被确定为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'),)),
)
键入代表真实数据格式的别名可能会有所帮助。虽然给出了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()
忽略和3.6之前的语法实际上并不需要单独的答案,它们已经存在于文档中,并且没有真正添加任何问题。