while expression feature proposal

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Oct 26 20:18:32 EDT 2012


On Fri, 26 Oct 2012 19:12:17 -0400, Devin Jeanpierre wrote:

> I would like a better iter(), rather than a better while loop. It is
> irritating to pass in functions that take arguments, and it is
> impossible to, say, pass in functions that should stop being iterated
> over when they return _either_ a None or a, say, False.

Write a trivial helper function. Not everything has to be a one-liner or 
a built-in.

def iterate_until_none_or_false(func, *args, **kwargs):
    while True:
        x = func(*args, **kwargs)
        # Halt if x is None or False, but not other falsey values.
        if x is None or x is False:
            return
        yield x

for x in iterate_until_none_or_false(
        some_function, 1, 2, "c", spam="yummy"):
    process(x)



-- 
Steven



More information about the Python-list mailing list