[Python] Is using assignment with yield (output = yield result) always unnecessary when there...

Discussão em 'Python' iniciado por Stack, Março 4, 2025.

  1. Stack

    Stack Membro Participativo

    def gen_with_feedback():
    feedback = yield "Start"
    print(f"Received feedback: {feedback}")

    result = feedback * 2
    output = yield result
    print(f"{output=}")
    yield

    gen = gen_with_feedback()
    # Start the generator and get the first yield ("Start")
    print(next(gen))

    return_value = gen.send(3)
    print(return_value)
    next(gen)


    Question

    Is output always unnecessary because it will always be None and should have used yield result without the assignment instead?

    Is there any documentation confirming that output here will be always None?

    Docs say (https://docs.python.org/3/reference/expressions.html#yield-expressions)


    If next() is used (typically via either a for or the next() builtin) then the result is None. Otherwise, if send() is used, then the result will be the value passed in to that method.
    ​

    However that describes the consumer -> generator direction, not generator -> consumer.


    Most explanations talk about output = yield result as a code pattern that receives some data sent from a consumer of a generator.

    In this example, receiving data from send() is already done by the line feedback = yield "Start".

    This question was inspired by bugs arising from forgetting to add an extra yield in the generator after feedback = yield "Start" to handle the fact that send will run until the next yield and pass the yielded value to the return value of send().

    yield result causes result to be passed from generator back to return_value in return_value = gen.send(3), so the direction of communication is reversed (generator to consumer).

    The final next(gen) was written just so print(f"{output=}") could run so I can see what's output.

    The final yield in gen_with_feedback was written to silence StopIteration to keep output cleaner. This is irrelevant to the question.

    Continue reading...

Compartilhe esta Página