example-code icon indicating copy to clipboard operation
example-code copied to clipboard

Mod : Example 16-17 grouper optimization

Open lbbc1117 opened this issue 8 years ago • 1 comments

The delegating generator grouper delegates averager inside a while loop. Every time averager returns, a new but useless averager instance will be created during the following loop period. Adding a yield statement after yield from averager() without while loop would be better. Great great book, by the way.

lbbc1117 avatar May 14 '17 12:05 lbbc1117

@ramalho i think the example should be this. currently, a new delegating generator is created for each item in data, which makes grouper's while loop unnecessary and creates the unused averager instance. grouper is also still active when the results are reported, though not sure if this matters as will be garbage collected once main() returns.

def grouper(results):
    while True:
        key = yield
        results[key] = yield from averager()

def main(data):
    results = {}
    group = grouper(results)
    next(group)
    for key, values in data.items():
        group.send(key)
        for value in values:
            group.send(value)
        group.send(None)
    group.close() # just to highlight that grouper is still an active generator

    report(results)

austinbravo avatar Feb 19 '20 20:02 austinbravo