[Python-ideas] for/else syntax

Yuvgoog Greenle ubershmekel at gmail.com
Sat Oct 3 17:52:24 CEST 2009


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.


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.
>
> Cheers,
> Nick.
>
> --
> Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
> ---------------------------------------------------------------
>



More information about the Python-ideas mailing list