Sobes.tech
Middle
206

Какова роль конструкции yield from в Python?

Answer from AI

sobes.tech AI

The yield from construct is used to delegate control of iteration from one generator (the delegating generator) to another generator or iterator (the subgenerator).

Main features of yield from:

  • Simplifies code reading: Replaces more complex logic of handling the subgenerator with explicit send and throw.
  • Automatically handles exceptions: Exceptions sent to the delegating generator are passed to the subgenerator.
  • Automatically handles the return value: The value returned by the subgenerator (via return) becomes the value of the yield from expression.
# Example without yield from (more complex)
def subgenerator_manual():
    yield 1
    yield 2
    return "Manual result"

def delegator_manual():
    sub = subgenerator_manual()
    try:
        value = next(sub)
        while True:
            try:
                sent = yield value
                value = sub.send(sent)
            except StopIteration as e:
                return e.value
    except StopIteration as e:
        return e.value

# Example with yield from (simpler)
def subgenerator_yield_from():
    yield 10
    yield 20
    return "Yield from result"

def delegator_yield_from():
    result = yield from subgenerator_yield_from()
    print(f"Subgenerator returned: {result}") # Displays the value returned by the subgenerator
    yield 30

# Usage
g_manual = delegator_manual()
print(list(g_manual))

g_yield_from = delegator_yield_from()
print(list(g_yield_from))

In the example with yield from, the main generator delegator_yield_from delegates iteration to subgenerator_yield_from. When subgenerator_yield_from finishes with a return, the returned value ("Yield from result") is assigned to the variable result in delegator_yield_from.