[Python-ideas] for/else syntax

MRAB python at mrabarnett.plus.com
Sat Oct 3 19:11:21 CEST 2009


Yuvgoog Greenle wrote:
> Ok, in theory, it's possible to flag a boolean after a for/while when
> compiling, but I think the "special syntax" option might be simpler to
> implement. So let's talk grammar...
> 
> The old grammar was:
> 
> while_stmt ::=  "while" expression ":" suite
>                 ["else" ":" suite]
> 
> for_stmt ::=  "for" target_list "in" expression_list ":" suite
>               ["else" ":" suite]
> 
> 
> And the new one I propose looks like this:
> 
> while_stmt ::=  "while" expression ":" suite
>                 ["if" expression ":" suite]
> 
> for_stmt ::=  "for" target_list "in" expression_list ":" suite
>               ["if" expression ":" suite]
> 
> 
> The "if" expression would be evaluated regularly but would have a
> magic boolean "break" that exists only in the if statement's
> expression eval. Note a few things:
> 1. the "if" would have been evaluated either way after the loop
> (exceptions/returns aside).
> 2. the only thing that's changed is the existence of the magic boolean "break".
> 3. You don't have to use it as the old "for...else" but you can and
> it's perfectly readable.
> 
> I'm no expert on the compiler, but I have a strong feeling this is doable.
> 
It means having to several tokens ahead before being able to tell
whether you're continuing the current structure or starting another.

Perhaps 'elif' instead?

while still_more_items():
     if found_it():
         break
elif not break:
     # exhausted search space

If the body of loop wasn't executed at all:

while still_more_items():
     if found_it():
         break
elif pass:
     # empty search space

> 
> On Sat, Oct 3, 2009 at 6:04 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
>> Yuvgoog Greenle wrote:
>>> I'd like to hear if people like this idea and if so, which of the 2
>>> options do you like better.
>> The compiler can't handle it - it will see the "if" as the start of a
>> new statement.
>>



More information about the Python-ideas mailing list