-1

Sometimes I need to consume everything that a generator outputs but don't actually need the output. In one case, some callers need progress updates from a coroutine, but some callers don't; in another case, some callers need to iterate through the results but some callers only need the side effects.

What's the idiomatic way to do this?

I currently use list():

def do_work_and_yield():
    for x in ...:
        y = do_work_on(x)
        yield y

def only_cares_about_side_effects():
    list(do_work_and_yield())

but of course this is an abuse of list() and a waste of memory. I could write a loop:

def only_cares_about_side_effects():
    for _ in do_work_and_yield():
        pass

but what I Really Mean is just "run do_work_and_yield to completion", which the loop obfuscates.

0

1 Answer 1

0

Naturally, the solution was hiding in the standard library documentation. The itertools docs give a recipe for a function called consume that does just what I want.

The "recipes" in the itertools documentation are conveniently available on PyPI in the more-itertools package.

So now I can just write

from more_itertools import consume

def do_work_and_yield():
    for x in ...:
        y = do_work_on(x)
        yield y

def only_cares_about_side_effects():
    consume(do_work_and_yield())
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.