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

Chris Angelico rosuav at gmail.com
Fri Apr 13 00:44:41 EDT 2018


On Fri, Apr 13, 2018 at 1:55 PM, Tim Peters <tim.peters at gmail.com> wrote:
> [David Mertz <mertz at gnosis.cx>]
>> Yes, I should have added ternary expressions to if statements. I can
>> definitely see the use there.
>>
>> However, your example is not null checking. You'd have to modify it slightly
>> to get that:
>>
>> None if var:= function() is None else var.method()
>>
>> Still not bad looking.
>
> I couldn't find text in the PEP spelling out precedence,

Oops, that's a mistake. I'll add that in a bit. It has extremely low precedence.

> but there are
> two plausible ways that could be grouped:
>
> 1.    None if (var:= function()) is None else var.method()
>
> which is what I believe you intended, and
>
> 2.    None if var:= (function() is None) else var.method()
>
> which from earlier iterations of this thread I believe is the actual
> meaning - but isn't at all what was intended.

I just went to test it, and the unparenthesized version is actually
bombing with SyntaxError. I'm going to call that a bug, though, and
see about fixing it tonight.

Currently, the precedence is so low that basically anything will get
captured, and if you want to capture anything less than the entire
expression, you parenthesize. I'll experiment with placing it between
'|' and comparison operators, which would mean that an unparenthesized
assignment expression generally won't capture a boolean, but will
instead capture the value itself. That's likely to be more useful, I
think. (Obviously you can always use parens to overrule the precedence
table.)

> While "assignment" is currently a statement type rather than "an
> operator", viewing the current situation as if "=" were an operator it
> has very low precedence, so it would be just as surprising at times to
> boost the precedence of ":=":
>
>      if x := i+1:
>
> That is, in _that_ example,
>
>     if x := (i+1):
>
> is "clearly intended", not the more tightly binding
>
>     if (x ;= i) + 1:

Agreed as regards addition. Less certain as regards comparisons.

if x := i > 1:

is currently "if x := (i > 1)" and not "if (x := i) > 1". Assuming I
don't run into implementation difficulties, I'll play with this
tonight, then document it one way or the other, and maybe have an open
question about the alternative precedence.

> On the third hand, requiring parentheses all the time would also feel strained:
>
>     while m := someregexp.match(somestring):
>
> is already impossible to misread.
>
> Annoying ;-)

Agreed. There's no reason to mandate the parens here. Neither the PEP
nor the reference implementation has any problem with this expression
being unparenthesized.

ChrisA


More information about the Python-ideas mailing list