[Python-ideas] "While" suggestion
George Sakkis
george.sakkis at gmail.com
Thu Jul 3 16:55:56 CEST 2008
On Thu, Jul 3, 2008 at 10:06 AM, Stavros Korokithakis <
stavros at korokithakis.net> wrote:
> Hello all,
> I have noticed that sometimes "while" loops produce "unpythonic" patterns,
> such as the following:
>
> data = my_file.read(1024)
> while data:
> do_something(data)
> data = my_file.read(1024)
>
> The assignment is repeated, which is less than optimal. Since we don't have
> a while statement that does the check in the end, would it not be better if
> the syntax of while could be amended to include something like this (in the
> spirit of the new "with" keyword)?:
>
> while my_file.read(1024) as data:
> do_something(data)
>
> This would terminate the loop when myfile.read() evaluated to False, and it
> is more pythonic than repeating onesself.
There is already an idiom for this, although admittedly not obvious or
well-known:
for data in iter(lambda: my_file.read(1024), ''):
do_something(data)
or in 2.5+:
from functools import partial
for data in iter(partial(my_file.read,1024), ''):
do_something(data)
George
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20080703/0ffdc2b6/attachment.html>
More information about the Python-ideas
mailing list