[Python-ideas] Spelling of Assignment Expressions PEP 572 (was post #4)
Steven D'Aprano
steve at pearwood.info
Fri Apr 13 07:04:32 EDT 2018
On Wed, Apr 11, 2018 at 03:32:04PM +1000, Chris Angelico wrote:
> In any context where arbitrary Python expressions can be used, a **named
> expression** can appear. This can be parenthesized for clarity, and is of
> the form ``(target := expr)`` where ``expr`` is any valid Python expression,
> and ``target`` is any valid assignment target.
Have we really decided on spelling this as `target := expression`? You
list this as a rejected spelling:
> 1. ``EXPR as NAME``, with or without parentheses::
>
> stuff = [[f(x) as y, x/y] for x in range(5)]
but I don't think the objections given should be fatal:
> Omitting the parentheses in this form of the proposal introduces many
> syntactic ambiguities. Requiring them in all contexts leaves open the
> option to make them optional in specific situations where the syntax is
> unambiguous (cf generator expressions as sole parameters in function
> calls), but there is no plausible way to make them optional everywhere.
>
> With the parentheses, this becomes a viable option, with its own tradeoffs
> in syntactic ambiguity. Since ``EXPR as NAME`` already has meaning in
> ``except`` and ``with`` statements (with different semantics), this would
> create unnecessary confusion or require special-casing.
The special casing you refer to would be to prohibit name binding
expressions in "except" and "with" statements. You should explicitly say
so in the PEP.
I don't think that prohibiting those two forms is a big loss. I think
any form of
except (name := expression) as err:
do_something(name)
is going to be contrived. Likewise for `with` statements.
I don't especially dislike := but I really think that putting the
expression first is a BIG win for readability. If that requires parens
to disambiguate it, so be it.
You also missed the "arrow assignment operator" from various languages,
including R:
expression -> name
(In an earlier post, I suggested R's other arrow operator, name <- expr,
but of course that already evaluates as unary minus expr.)
I think that there should be more attention paid to the idea of putting
the expression first, rather than the name.
--
Steve
More information about the Python-ideas
mailing list