Clearly the PEP should spell out the precedence of :=. I'm sure Chris
intended to give := the lowest possible precedence: the analogy with =
(both in Python and in other languages), and the original design of the
PEP, where the syntax was (<expr> as <var>), with mandatory parentheses.
(Probably his implementation helps to guess his intention too, but I can't
be bothered yet to clone and build it just to answer this question
definitively. :-)
I find the analogy argument compelling, and I think we should just make it
a style rule that parentheses should be used whenever it could be misread
by a human who's not sure about the precedence.
Too bad for that one example.
On Thu, Apr 12, 2018 at 9:14 PM, David Mertz
Yes, I have not read all the iterations of the PEP, and none of them extremely closely. I had thought it "obvious" that ':=' should have a very high operator precedence. But of course if it doesn't then expressions like the one I proposed could mean something quite different.
I find the third hand argument rather compelling. All those potentially required parentheses turn elegant looking code into an ugly mess.
On Thu, Apr 12, 2018, 11:56 PM Tim Peters
wrote: [David Mertz
] 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 ;-)
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/
-- --Guido van Rossum (python.org/~guido)