[Python-ideas] "While" suggestion

Stavros Korokithakis stavros at korokithakis.net
Thu Jul 3 18:06:22 CEST 2008


Hmm, the regular expression use case (and any other use case where you 
need to act based on the output of a function) looks very interesting, 
but I can understand how there would be a few problems with it for 
things like "if myfunc() > 10 as output".

Still, it is worth investigating.

Stavros

Mike Meyer wrote:
> On Thu, 3 Jul 2008 11:46:51 -0300 "Facundo Batista" <facundobatista at gmail.com> wrote:
> 
>> 2008/7/3 Stavros Korokithakis <stavros at korokithakis.net>:
>>
>>> while my_file.read(1024) as data:
>>>   do_something(data)
>> Python explicitly disallows inline assignment ("while
>> a=myfile.read():") because of the error propensity when confusing it
>> with the comparation ("=="). But here we're gaining the same
>> advantage, without that risk.
>>
>> So, taking into account that...
>>
>> a) We already have "as" as an statement.
>>
>> b) We already use "as" as an assignment [1]
>>
>> c) This will allow more concise and intuitive code
>>
>> ... I'm definitely +1 to this proposition.
>>
> 
> I kinda like it as well. In fact, treating "as" as an assignment
> operator instead of making it part of the syntax of the while
> statement solves my problem with the suggestion.
> 
> The original suggestion only dealt with a *very* special case: a loop
> where 1) you needed to initialize the data before the loop started; 2)
> the initialization statement was use to refresh the data in the loop,
> and 3) the value of the data as a bool determined whether you wanted
> to continue.
> 
> If #3 isn't true, a while+as statement leaves you back at the original
> code duplication. as as inline assignment it lets you deal with it
> without the repitition:
> 
> while my_file.read(1024) as data < 1024:
>       do_something_with_1k(data)
> do_something_with_lessthan_1k(data)
> 
> It also provides a nice way to deal with the long-standing ugliness
> related to wanting to do repeated regular expression tests:
> 
> if myre.match(user_input) as match:
>    do_something_with_matching_data(match)
> elif myre2.match(user_input) as match:
>    do_something_else(match)
>    
> instead of:
> 
> match = myre.match(user_input)
> if match:
>    do_something_with_matching_data(match)
> else:
>    match = myre2.match(user_input)
>    if match:
>       do_something_else(match)
> 
> which doesn't yield to the usual solution of a dict of functions.
> 
>> In any case, Stavros, this would need a PEP...
> 
> I'm not convinced (it ought to interact cleanly with with, but....),
> but it certainly looks promising!
> 
> +1 to at least investigating it.
> 
>     <mike
-------------- next part --------------
A non-text attachment was scrubbed...
Name: stavros.vcf
Type: text/x-vcard
Size: 143 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20080703/ffcb5e31/attachment.vcf>


More information about the Python-ideas mailing list