[Python-Dev] PEP 572: Assignment Expressions

Christoph Groth christoph at grothesque.org
Sat Apr 21 08:28:32 EDT 2018


Tim Peters wrote:
> [Chris Angelico <rosuav at gmail.com>]
> > I don't see much value in restricting the assignment target to names
> > only, but if that's what it takes, it can be restricted, at least
> > initially.
>
> I believe this point was made most clearly before by Terry Reedy, but
> it bears repeating :-)  This is from the PEP's motivation:
>
> """
> Naming the result of an expression is an important part of
> programming, allowing a descriptive name to be used in place of a
> longer expression, and permitting reuse.
> """
>
> As "head arguments" go, that's a good one!  But restricting assignment
> expressions to
>
>     identifier ":=" expression
>
> satisfies it.  If what's of value is to name the result of an
> expression, that single case handles that and _only_ that.  In a
> sense, it's "the simplest thing that could possibly work", and that's
> generally a good thing to aim for.
>
> (...)

Tim, thanks for this clear analysis.  Here's the best use case of more
general assignment expressions that I can come up with (from real code
I'm currently working on):

class Basis:
    def __init__(self, parent, periods=()):
        self._parent = parent
        if len(self._periods := np.asarray(periods, int)):
            ...
        else:
            # In absence of periods, treat them as an (0, n)-shaped array.
            # This avoids a special code path below.
            self._periods = np.empty((0, len(parent.periods)), int)

But since this is a weak counterexample, it actually serves to
strengthen your point that

    identifier ":=" expression

is all that is needed.

Such minimal assignment expressions have the (IMHO important) advantage
of not being inconsistent with assignment statements.

----------------

Still, it seems weird to have two different ways of binding names in the
language where one would be sufficient (i.e. the old one would remain
only for backwards compatibility).  From the point of view of someone
who's new to the language that's two things to learn instead of just
one.


More information about the Python-Dev mailing list