2016-09-18 19 views
4

をヒント私はこの非常に単純なコードがあります。`のIterable [(int型、int型)]`タプルがタイプで許可されていませんが

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のペアのiterableを持っていますか?

-> PositionIterable[Any]の両方の仕事は、ちょうどIterablePositionではありません。

答えて

6

タプルタイプPosition(int, int)ではなく)を宣言するには、typing.Tuple[int, int]を使用する必要があります。

+0

しかし、 'foo() - >(int、int)'は 'foo() - > Iterable [(int、int)]'ではなく '働くのはなぜですか? – Caridorc

+4

機能アノテーションは何もしません。彼らは純粋に情報的なものです。任意のPythonオブジェクトを型ヒントとして使うことができます。 '(int、int)'は確かに有効なPythonオブジェクトです。 ' - > 42'や' - > super'を使うこともできます。これはあまり役に立ちませんが、構文的には正しいでしょう。一方、 'typing.Iterable'は、より具体的には、関数注釈における型ヒントを意味し、' typing'モジュール内の他の型注釈クラスと一緒に働くように設計されています。 –

+0

非常に明確になりました。ありがとう、良い一日を。 – Caridorc

関連する問題