Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to desugar a yield from syntax in Python?

Now I'm studying on the differences between a yield-from and an await syntax. From the official python documentation, the yield-from generator() is just a syntax suger of the following code:

for i in generator(): yield i

But I can't desugar the yield-from in the example below.

def accumlate():
    # context
    accumlator = 0
    while True:
        next = yield
        if next is None:
            return accumlator
        accumlator += next


def gather(tallies):
    while True:
        tally = yield from accumlate() # (*)
        tallies.append(tally)

def main():
    tallies = []
    accumlator = gather(tallies)
    next(accumlator)
    for i in range(4):
        accumlator.send(i)

    accumlator.send(None)
    for i in range(6, 10):
        accumlator.send(i)
    accumlator.send(None)
    print(tallies)

if __name__ == "__main__":
    main()

I tried to just replace a yield-from with the for-in version, but it did't work because the for-in can't be placed on the right side of the tally variable. What is an exact desugar of the code marked with asterisk ?

like image 635
BrainVader Avatar asked Apr 23 '26 12:04

BrainVader


1 Answers

@DerteTrdelnik's answer is largely correct, except that you don't have to modify the accumlate function at all, since a generator would already automatically raise StopIteration with the returning value as a parameter to construct the exception object when the generator returns without a yield.

Excerpt from the documentation of StopIteration:

When a generator or coroutine function returns, a new StopIteration instance is raised, and the value returned by the function is used as the value parameter to the constructor of the exception.

Therefore, you only need to "desugar" the gather function as such:

def gather(tallies):
    while True:
        a = accumlate()
        a.send(None)
        while True:
            try:
                a.send((yield))
            except StopIteration as e:
                tallies.append(e.value)
                break
like image 179
blhsing Avatar answered Apr 26 '26 01:04

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!