[Python-Dev] PEP 572: Assignment Expressions

Tim Peters tim.peters at gmail.com
Fri Apr 20 22:15:32 EDT 2018


[Tim]
>> And I'll take this opportunity to repeat the key point for me:  I
>> tried hard, but never found a single case based on staring at real
>> code where allowing _fancier_ (than "plain name") targets would be a
>> real improvement.  In every case I thought it _might_ help, it turned
>> out that it really didn't unless Python _also_ grew an analog to C's
>> "comma operator" (take only the last result from a sequence of
>> expressions).  I'll also note that I asked if anyone else had a
>> real-life example, and got no responses.

[MRAB <python at mrabarnett.plus.com>]
> Could a semicolon in a parenthesised expression be an equivalent to C's
> "comma operator"?

I expect it could, but I it's been many years since I tried hacking
Python's grammar, and I wouldn't want a comma operator anyway ;-)

To recycle a recently-posted example, instead of one of these 3:

    if ((a, b, c) := func_returning_triple()) and b > 0:
        process(a+b, b+c, a+c)

    if ((a, b, c) := func_returning_triple())[1] > 0:
        ....

    if [((a, b, c) := func_returning_triple()), b > 0][-1]::
        ...

it would allow this instead:

    if ((a, b, c) := func_returning_triple(); b > 0):
        ...

That's better than any of the first three, but I'm not sure it's
better than the original

    a, b, c = func_returning_triple()
    if b > 0:
        ...

It _may_ be more readable in other complex-target examples, though.

It's also what's wanted in one of the running plain-name target
examples, _not_ involving a conditional context:

    r1, r2 = (D := sqrt(b**-4*a*c); a2 := 2*a; ((-b+D)/a2), (-b-D)/a2))

And if I saw enough code like that, I'd write a PEP suggesting that
Python introduce separate assignment statements where name bindings
persisted across statement boundaries ;-)


More information about the Python-Dev mailing list