[Python-Dev] (name := expression) doesn't fit the narrative of PEP 20

Antoine Pitrou solipsis at pitrou.net
Thu Apr 26 04:30:59 EDT 2018


On Thu, 26 Apr 2018 17:29:17 +1000
Steven D'Aprano <steve at pearwood.info> wrote:
> On Thu, Apr 26, 2018 at 07:16:28PM +1200, Greg Ewing wrote:
> > Tim Peters wrote:  
> > >As a statement in a program (as opposed to typed at a shell),
> > >"a := 3" has the unnecessary (in that context) property of returning
> > >(and discarding 3), so it's better style to use "a = 3" in that
> > >context.  
> > 
> > That seems like a post-hoc justification. If := were the one
> > and only assignment symbol, the compiler could easily optimise
> > away the extra DUP_TOP or whatever is involved.  
> 
> Its still bad form to rely on compiler-dependent optimizations which 
> aren't part of the language specification.

If such were the need, you could very well make it part of the language
specification.  We are talking about a trivial optimization that any
runtime could easily implement (e.g. if a sequence `DUP_TOP, STORE_FAST,
POP_TOP` occurs, replace it with `STORE_FAST`).

Any runtime already has to implement a set of performance properties
that's far less trivial than that.  For example, any decent runtime is
expected to provide amortized O(1) list append or dict insertion.  You
are breaking user expectations if you don't.

> And to steal an earlier idea from Tim, it is especially unfortunate if 
> you copy
> 
> data := sorted(huge_list_with_billions_of_items)
> 
> from a program and paste it into your REPL, then can't type again for an 
> hour or two.

Well, how do languages where assignment is an expression returning the
assigned value make their REPLs work?  I'm sure they don't inflict that
on their users, so it's certainly a solvable problem.

(abstractly: if the user is executing a top-level assignment expression,
don't display the assignment result)

> The longer I think about this, the more I am convinced that having two 
> forms of assignment, one a statement with no return value and the other 
> an expression with a return value, is a feature, not a wart or bug.

Yet, curiously, no other language seems to replicate that "feature" :-)

It's nice to innovate, but being the only one to do something may very
well mean that you're doing something ridiculous.

Regards

Antoine.




More information about the Python-Dev mailing list