Is this PEP-able? fwhile

wu wei wuwei23 at gmail.com
Mon Jun 24 20:41:13 EDT 2013


On Tue, Jun 25, 2013 at 10:19 AM, Fábio Santos <fabiosantosart at 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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130625/75f68e76/attachment.html>


More information about the Python-list mailing list