88514


実行環境: Python 3.10.4

[code]

    >>> def pro(value):
    ...     if value == 5:
    ...         return ['Python']
    ...     else:
    ...         yield from range(value)
    >>> pro(5)
    <generator object pro at 0x000001F1E696AC70>
    
[/code]

を実行するとジェネレータオブジェクトが返されます．内部で何が起こっているのですか．


CC BY-SA 4.0
2022-04-26T03:10:33.697
88501
2022-04-26T07:59:01.530
51374
question
python python3
returnとyield fromの同時使用について


`yield`式 (`yield`文も意味は同じ) があると Generatorsです。

  * [6.2.9. Yield 式](https://docs.python.org/ja/3/reference/expressions.html#yield-expressions) / [7.7. yield 文](https://docs.python.org/ja/3/reference/simple_stmts.html#the-yield-statement)
  * <https://docs.python.org/ja/3/tutorial/classes.html#generators>

この場合の returnは, `StopIteration` 送出の意味

[code]

    def fn(value):
        print('=> start generator')
        for n in range(value):
            yield n
        return '== 停止 =='
    
    gen = fn(3)
    for n in gen:
        print(n)
    # => start generator
    # 0
    # 1
    # 2
    
    gen = fn(1)
    print(next(gen))
    # => start generator
    # 0
    print(next(gen))
    # ---------------------------------------------------------------------------
    # StopIteration                             Traceback (most recent call last)
    # StopIteration: == 停止 ==
    
[/code]

類似質問: [yieldとreturnを併用したい](https://ja.stackoverflow.com/questions/51410/)

yield fromは, サブジェネレータへの委譲です

[code]

    def subgen():
        yield 100
        yield from 'やあ'
        return
    
    def fn(value):
        print('=> start generator')
        yield from subgen()
        return '== 停止 =='
    
    for n in fn(100):
        print(n)
    
    # => start generator
    # 100
    # や
    # あ
    
[/code]


CC BY-SA 4.0
2022-04-26T07:59:01.530
88514
2022-04-26T07:59:01.530
43025
88501
answer