[Python-ideas] A PEP on introducing variables on 'if' and 'while'

Steven D'Aprano steve at pearwood.info
Sun Jun 10 09:19:58 EDT 2018


On Sun, Jun 10, 2018 at 08:08:13AM -0400, Juancarlo Añez wrote:

> >     while (condition := expression) as flag:
> >         ...
> >
> 
> Ah! Are the parenthesis necessary there?

It's your PEP, you tell us.


> > Accepting "while/if as name" would remove much (but not all) of the
> > motivation for assignment expressions, while accepting assignment
> > expressions would make a dedicated while/if as name syntax unnecessary.
> 
> Most of the arguments in favor of ':=' have been through examples of
> generators in which the introduced name is used within, with the if/while
> case often forgotten.

Indeed. I think that the generator/comprehension use-cases for 
assignment expressions are not the most compelling. They're important, 
but at the point you need to use assignment inside a comprehension, 
there's a good argument that it *may* be time to refactor to a loop. I 
think the while/if examples are even more important.


> There can be cases in which combining both syntaxes is useful:
> 
> x = None
> while compute(x := v for v in next_series_value(x)) as comp:
>     ...
>     x = comp


But if you have assignment expressions, you don't need "as".

x = None
while comp := compute(x := v for v in next_series_value(x)):
    ...
    x = comp


> Finding a real-world example of something like the above synthetic example
> would be in favor of the orthogonality.

As the PEP author, that's your job.


-- 
Steve


More information about the Python-ideas mailing list