【问题标题】:`Iterable[(int, int)]` tuple is not allowed in type hints`Iterable[(int, int)]` 元组不允许出现在类型提示中
【发布时间】:2017-01-26 12:59:51
【问题描述】:

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

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)

这是错误:

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

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

-&gt; PositionIterable[Any] 都可以工作,只是 IterablePosition 不能一起工作。

【问题讨论】:

    标签: python python-3.5 type-hinting


    【解决方案1】:

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

    【讨论】:

    • 但是为什么foo() -&gt; (int, int) 有效,而不是foo() -&gt; Iterable[(int, int)]
    • 函数注解不做任何事情;它们纯粹是信息性的。您可以使用任何 Python 对象作为类型提示,(int, int) 肯定是一个有效的 Python 对象。您也可以使用-&gt; 42-&gt; super。它不会很有用,但在语法上是正确的。另一方面,typing.Iterable 更具体地用于函数注释中的类型提示,它旨在与 typing 模块中的其他类型注释类一起使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多