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

Chris Angelico rosuav at gmail.com
Wed Apr 11 09:54:40 EDT 2018


On Wed, Apr 11, 2018 at 11:37 PM, Paul Moore <p.f.moore at gmail.com> wrote:
> 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.

Sure, if you're just assigning zero to everything. But you could do
that with a statement. What about this:

q = {
    lambda: x := lambda y: z := a := 0,
}

Yes, it's an extreme example, but look at all those colons and tell me
if you can figure out what each one is doing.

ChrisA


More information about the Python-ideas mailing list