[Python-Dev] PEP 572: Assignment Expressions (original) (raw)

Tim Peters tim.peters at gmail.com
Sat Apr 21 15:20:21 EDT 2018


[Christoph Groth <christoph at grothesque.org>]

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.

That's a decent example. In truth, I have no real objection to binding an attribute - but am willing to throw out a bit of soap with the bathwater if doing so can avoid throwing the baby out too ;-)

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.

But they're very different in a key respect. the value of an assignment expression is the value assigned. Asking "what's the value of a statement?" doesn't even make sense in Python (whether an assignment statement or any other kind of statement).

For that reason, if a PEP is reworked to suggest a "binding expression" (I'd prefer the name change to nudge people away from conflating it with the far more general assignment statement), the usage pragmatics are clear: use a binding expression if the context requires using the value bound, else use a simple assignment statement.

":=" doesn't just mean "bind the simple name on the left" in that world, but also "and return the value of the expression on the right".

For that reason, e.g.,

i = 1

would be strongly preferred to

i := 1

as a standalone line, except perhaps when typing at an interactive shell (where you may want to see the value being bound - but usually don't).



More information about the Python-Dev mailing list