[Python-Dev] assignment expressions: an alternative proposal

Eric Snow ericsnowcurrently at gmail.com
Tue Apr 24 10:54:52 EDT 2018


Thanks for thinking this through, Yury. :)

FWIW, I'm still unconvinced that an assignment expression is worth it.
It's hard to say, though, without seeing how much folks would actually
use it (and I don't have my own time machine unfortunately).  IIRC, in
the past several proposed syntax (e.g. decorators) were in the same
boat and in retrospect turned out to be a strongly positive addition
to the language. :)

Comments in-line below.

-eric

On Tue, Apr 24, 2018 at 7:38 AM, Yury Selivanov <yselivanov.ml at gmail.com> wrote:
> I propose to use the following syntax for assignment expressions:
>
>     ( NAME = expr )
>
> [snip]
>
> 1. Only NAME token is allowed as a single target.

This seems reasonable and does keep assignment expressions easier for
the reader to find.  At the same time, there have been some arguments
elsewhere in favor of tuple unpacking as the other obvious use case.
Presumably that would not be supported under this rule.

> 2. Parenthesis are required.

Similar to rule #1, this would make assignment expressions more
obvious to readers, which is a good thing.

>
> 3. Most importantly: it is *not* allowed to mask names in the current
> local scope.

I was about to leave this counter example for
accidentally-typed-one-equal-sign-instead-of-two bugs:

    if (y == 3):
        print(y)
    # vs.
    if (y = 3):
        print(y)

Then it dawned on me that your rule #3 solves this. :)

> [snip]
>
> py> f = lambda x: x * 10
> py> [[(y = f(x)), x/y] for x in range(1,5)]
> [[10, 0.1], [20, 0.1], [30, 0.1], [40, 0.1]]
>
> [snip]
>
> I believe that this syntax is the best of both worlds: it allows to
> write succinct code just like PEP 572, but without introducing a new
> ':=' operator.

This is the main point of this alternate proposal, right?  It
certainly seems reasonable that we not add another assignment syntax.
On the other hand, having ":=" as a distinct syntax for assignment
expressions is close enough to the existing syntax that it doesn't
really add any real extra burden to readers, while being more
searchable and visually distinct.  If we were to add assignment
expressions I'd probably favor ":=".

Regardless, your 3 rules would benefit either syntax.  Nick may have a
point that the rules might be an excessive burden, but I don't think
it's too big a deal since the restrictions are few (and align with the
most likely usage) and are limited to syntax so the compiler will be
quick to point mistakes.


More information about the Python-Dev mailing list