[Python-ideas] Filtered "for" loop with list-comprehension-like syntax

Ben Finney ben+python at benfinney.id.au
Sat May 21 03:51:51 CEST 2011


Dan Baker <dbaker3448 at gmail.com> writes:

> It seems odd that "for x in y if z" is allowed in comprehensions but
> not in a regular for loop. Why not let
>
> for x in y if z:
>    do_stuff(x)
>
> be a shorthand for
>
> for x in y:
>    if not z:
>       continue
>    do_stuff(x)

This can already be spelled:

    for x in (w for w in y if z):
        do_stuff(x)

Which is not to forestall discussion of the proposed language change,
but only to point out that there is an existing idiom for this.

> Similarly, I occasionally have multiple sections that need to be
> handled differently. One way to write this is:
> for line in input_file:
>    if is_section_delimiter(line):
>       break
>    do_stuff_1(line)
> for line in input_file: # this picks up where the last one left off
>    if is_section_delimiter(line):
>        break
>    do_stuff_2(line)
> etc.

That looks like it would be better modelled with an explicit state
transition when the condition is encountered, without stopping the
iteration:

    handlers = [do_stuff_1, do_stuff_2, do_stuff_3]
    handle_line = handlers.pop(0)
    for line in input_file:
        if is_section_delimiter(line):
            handle_line = handlers.pop(0)
        handle_line(line)

-- 
 \       “Philosophy is questions that may never be answered. Religion |
  `\              is answers that may never be questioned.” —anonymous |
_o__)                                                                  |
Ben Finney




More information about the Python-ideas mailing list