On Tue, Jun 25, 2013 at 10:19 AM, Fábio Santos <fabiosantos...@gmail.com>
 wrote:

> for X in (i for i in open('largefile') if is_part_of_header(i)):
>
> The above code would be wasting time on IO and processing. It would load
> another line and calculate the condition for every line of the large file
> and I just wanted to loop over the few header lines.
>
> itertools.takewhile and fwhile/for..while actually stops the loop when the
> condition is not meant, while your example keeps checking the condition
> until the end of file, even though it is a generator expression.
>
Ah yes, of course, my bad.

It's still possible by raising a StopIteration within the condition
function:

    def is_part_of_header(x):
        if header_condition:
            return True
        else:
            raise StopIteration

But yes, by this point any clarity of the generator expression approach
comes with the cost of more explicit setup of the breaking condition.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to