[Python-ideas] PEP 572: Assignment Expressions (post #4)
Tim Peters
tim.peters at gmail.com
Thu Apr 12 23:55:47 EDT 2018
[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, 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.
The most clearly related example in the PEP appears to be:
x = "default" if (eggs := spam().ham) is None else eggs
which forced the intended meaning as in #1 above.
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:
On the third hand, requiring parentheses all the time would also feel strained:
while m := someregexp.match(somestring):
is already impossible to misread.
Annoying ;-)
More information about the Python-ideas
mailing list