`Iterable [(int,int)]`tuple在类型提示中是不允许的

Car*_*orc 5 python typing python-3.5

我有这个非常简单的代码:

from typing import List, Iterable

Position = (int, int)
IntegerMatrix = List[List[int]]

def locate_zeros(matrix: IntegerMatrix) -> Iterable[Position]:
    """Given an NxM matrix find the positions that contain a zero."""
    for row_num, row in enumerate(matrix):
        for col_num, element in enumerate(row):
            if element == 0:
                yield (col_num, row_num)
Run Code Online (Sandbox Code Playgroud)

这是错误:

Traceback (most recent call last):
  File "type_m.py", line 6, in <module>
    def locate_zeros(matrix: IntegerMatrix) -> Iterable[Position]:
  File "/usr/lib/python3.5/typing.py", line 970, in __getitem__
    (len(self.__parameters__), len(params)))
TypeError: Cannot change parameter count from 1 to 2
Run Code Online (Sandbox Code Playgroud)

为什么我不能将一对可迭代的Int对作为返回类型?

无论-> PositionIterable[Any]工作,只是没有IterablePosition在一起没有.

Sve*_*ach 8

您应该使用typing.Tuple[int, int]声明元组类型Position,而不是(int, int).

  • 但为什么 `foo() -&gt; (int, int)` 可以工作,而不是 `foo() -&gt; Iterable[(int, int)]` 呢? (5认同)
  • 函数注释不做任何事情; 他们纯粹是信息性的.您可以使用任何Python对象作为类型提示,而`(int,int)`肯定是一个有效的Python对象.你也可以使用` - > 42`或` - > super`.它不是很有用,但在语法上是正确的.另一方面,`typing.Iterable`更具体地用于函数注释中的类型提示,它被设计为与`typing`模块中的其他类型注释类一起工作. (5认同)