[Python-ideas] "While" suggestion

Chris Rebert cvrebert at gmail.com
Thu Jul 3 17:32:43 CEST 2008


On Thu, Jul 3, 2008 at 7: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)


What if the condition is ever so slightly more complicated? Then it
looks a bit less than natural...

while foo() != 17 as baz:
    do_something(baz)

Now it looks like baz should equal the boolean value from the
comparison, but what if i want it to be foo() ? And if it is somehow
magically foo(), then that's really unintuitive-looking.

- Chris

>
> This would terminate the loop when myfile.read() evaluated to False, and it
> is more pythonic than repeating onesself.
>
> I contacted GvR about this, and he replied that this syntax would have to be
> part of the expression than part of the while, which I agree would be less
> than ideal. However, I don't see why it would have to be part of the
> expression, since the "while" could easily assign the value of the
> expression to the variable and break if it evaluates to False.
>
> I would appreciate any thoughts on this,
> Stavros Korokithakis
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
>



More information about the Python-ideas mailing list