[Python-ideas] "While" suggestion

Jacob Rus jacobolus at gmail.com
Tue Jul 29 03:53:32 CEST 2008


Andrew Akira Toulouse wrote:
> Your counterpoint takes exception to the example rather than the suggestion.
> Say someone is going through a flat file with a large list of numbers, and
> they want to filter out all odd numbers, and stop once they encounter a 0
> value.  [...]
> 
> [int(line) for line in file if evenP(int(line)) until int(line)==0 with
> open(filename) as file]
> 
> Bam, one line to open the file, iterate through them, filter out unneeded
> entries, define the base case, and return value.
> 
> Do you believe that this also abuses list comprehensions? If so, please
> explain your reasoning.
> 
> There's nothing keeping a programmer from writing anything this syntax could
> do as a normal for loop, but neither is there anything stopping said
> programmer from using a for loop with ifs and breaks in place of a list
> comprehension.

Since you don't like for loops, what's wrong with:

     from itertools import takewhile

     with open(filename) as f:
         intlines = (int(line) for line in f if evenP(int(line)))
         result = list(takewhile(lambda x: x, intlines))

This is perfectly clear, not too much longer than your suggestion, and 
doesn't require adding large amounts of extra syntax to the language 
(though using a lambda for the identity function is a bit more verbose 
than I'd prefer).

Personally, I’d rather have this broken up than in one gigantic line 
that looks like:

     result = [int(line) for line in f if evenP(int(line))
               until int(line) == 0 with open(filename) as f]

As for:

>     tokenchecks = [token for regex,token in match_tok until regex.match(s)] 
>     return tokenchecks[-1]

This is much more readably expressed as:

for regexp, token in match_tok:
     if regexp.match(s):
         return token


Cheers,
Jacob Rus




More information about the Python-ideas mailing list