2017-04-27 4 views
6

私は、ジェネレータ機能のためにタイプヒント:rtype:を書こうとしています。それが返すタイプは何ですか?例えばジェネレータ関数の戻り値のヒントは何ですか?

、私は文字列を生成し、この機能を持っていると言う:

def read_text_file(fn): 
    """ 
    Yields the lines of the text file one by one. 
    :param fn: Path of text file to read. 
    :type fn: str 
    :rtype: ???????????????? <======================= what goes here? 
    """ 
    with open(fn, 'rt') as text_file: 
     for line in text_file: 
      yield line 

戻り値の型は、それは文字列の反復可能ないくつかの種類の単なる文字列ですされていませんか?だから私は:rtype: strと書くことはできません。正しいヒントは何ですか?

+0

あなたは型ヒントを求めていないように見えます –

+0

文字列で発電機を返しますが、 'のdocstring挿入:RTYPE:' –

答えて

4
+0

私は、これはエラー原因だと思う: 'TypeError例外を:あまりにもタイピングのためのいくつかのパラメータ。 'Generator'は' yield'と 'send'と' return'の型を期待しています(ジェネレータ[Generator [Generator [ yield_type、send_type、return_type] ') –

3

発電機に注釈を付けるための一般的なタイプはtypingモジュールで提供Generator[yield_type, send_type, return_type]です:

def echo_round() -> Generator[int, float, str]: 
    res = yield 
    while res: 
     res = yield round(res) 
    return 'OK' 

代わりにあなたがIterable[YieldType]Iterator[YieldType]を使用することができます。