[Python-ideas] PEP 572: about the operator precedence of :=
Guido van Rossum
guido at python.org
Wed May 9 23:33:05 EDT 2018
(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)
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas