Is there a more appropriate mechanism to showing support for a 'EXPR given
x = EXPR' approach, as suggested by Nick Coghlan? Then, keeping the binding rules the same for statement assign, requiring parenthesis, would keep things consistent. I personally prefer it to := for the reasons I mentioned previously. Angus Hollands
Date: Wed, 9 May 2018 20:33:05 -0700 From: Guido van Rossum email@example.com To: Python-Ideas firstname.lastname@example.org Subject: [Python-ideas] PEP 572: about the operator precedence of := Message-ID: < CAP7+vJJSDeL0FWiYDhRfkgfxGX-oKKynfzyF3fHS+kkjb6DePA@mail.gmail.com> Content-Type: text/plain; charset="utf-8"
(I vaguely recall this has been brought up before, but I'm too lazy to find the subtread. So it goes.)
PEP 572 currently seems to specify that when used in expressions, the precedence of `:=` is lower (i.e. it binds more tightly) than all operators except for the comma. I derive this from the single example `stuff = [[y := f(x), x/y] for x in range(5)]`.
From this it would follow that `f(a := 1, a)` is equivalent to `a = 1;
f(1, 1)`, and also that `(a := 1, a)` is equivalent to `a = 1; (1, 1)`. (Although M.A.L. objected to this.)
But what should `a := 1, 1` at the top level (as a statement) do? On the one hand, analogy with the above suggest that it is equivalent to `a = 1; (1, 1)`. But on the other hand, it would be really strange if the following two lines had different meanings:
a = 1, 1 # a = (1, 1) a := 1, 1 # a = 1; (1, 1)
I now think that the best way out is to rule `:=` in the top level expression of an expression statement completely (it would still be okay inside parentheses, where it would bind tighter than comma).
An alternative would be to make `:=` bind less tight than comma (like `=`) everywhere, so that `a := 1, 1` indeed meant the same as `a = 1, 1`. But that feels very wrong at least for the case `f(a := 1, 1)` -- I believe Tim already mentioned that we've been conditioned by keyword arguments to parse this as `f((a := 1), 1)`. (I could add to this that we have done various things to generator expression syntax to avoid ever having to deal with ambiguities like `a, a+1 for a in range(10)` or `a for a in x, y`.)
Another alternative would be to always require parentheses around `:=`, so that we would have to write `f((a := 1), 1)`. That's unambiguous, but otherwise just gets on the nerves.
-- --Guido van Rossum (python.org/~guido)