[Python-ideas] PEP 572: Assignment Expressions (post #4)

Paul Moore p.f.moore at gmail.com
Wed Apr 11 09:37:56 EDT 2018


On 11 April 2018 at 14:25, Chris Angelico <rosuav at gmail.com> wrote:
> On Wed, Apr 11, 2018 at 10:23 PM, Clint Hepner <clint.hepner at gmail.com> wrote:
>>> Differences from regular assignment statements
>>> ----------------------------------------------
>>>
>>> An assignment statement can assign to multiple targets::
>>>
>>>    x = y = z = 0
>>>
>>> To do the same with assignment expressions, they must be parenthesized::
>>>
>>>    assert 0 == (x := (y := (z := 0)))
>>
>> There's no rationale given for why this must be parenthesized.
>> If := were right-associative,
>>
>>     assert 0 == (x := y := z := 0)
>>
>> would work fine. (With high enough precedence, the remaining parentheses
>> could be dropped, but one would probably keep them for clarity.)
>> I think you need to spell out its associativity and precedence in more detail,
>> and explain why the rationale for the choice made.
>
> It's partly because of other confusing possibilities, such as its use
> inside, or capturing, a lambda function. I'm okay with certain forms
> requiring parens.

The only possible reading of

    x := y := z := 0

is as

    x := (y := (z := 0))

because an assignment expression isn't allowed on the LHS of :=. So
requiring parentheses is unnecessary. In the case of an assignment
statement, "assignment to multiple targets" is a special case, because
assignment is a statement not an expression. But with assignment
*expressions*, a := b := 0 is simply assigning the result of the
expression b := 0 (which is 0) to a. No need for a special case - so
enforced parentheses would *be* the special case.

And you can't really argue that they are needed "for clarity" at the
same time as having your comments about how "being able to write ugly
code" isn't a valid objection :-)

Paul


More information about the Python-ideas mailing list