[Python-Dev] PEP 572: Assignment Expressions

Tim Peters tim.peters at gmail.com
Mon Apr 23 17:41:49 EDT 2018


[Tim]
>> Surely you're joking.  This is math.gcd(), which is expensive for
>> multi-thousand bit integers, and the interpreter knows nothing about
>> it.  Adding a cache of _any_ kind (LRU or otherwise) would make it
>> even slower.

[Sven R. Kunze <srkunze at mail.de>]
> Alright, if that problem is just about performance,

It's not, but others had already pointed out that it's generally
considered Poor Practice (and for good reasons) to textually repeat
expressions, so I didn't echo that.  Even in purely functional
languages, where textually equal snippets are guaranteed to evaluate
to the same result every time, "give these expressions these brief
names" constructs are heavily used (see, .e.g, "let" and "where" in
Haskell).


>:then there must be a better way to resolve it rather than
> inventing a new syntax.

Why?  "Give the result of an expression a name" is already heavily
used in Python - it's just that the _contexts_ in which it can be done
are very limited now.


> Btw. storing the result in a local var is also a cache IMHO. And
> if gcd is immutable, I think Python can do a great job here of
> optimizing.

After decades, CPython still does nothing of the sort, short of having
eventually made, e.g., "None" and "True" and "False" reserved words so
at least it can optimize uses of those.  It knows nothing at all about
which library functions are pure - and there's no code in the
implementation currently capable of exploiting such information even
if it were known.  That remains a fantasy in CPython.


> Anyway, your example is the best one I've seen so far.

Guido gave better ones, where binding expressions would allow to
collapse arbitrarily deep levels of nesting to just one (if ... elif
... elif ... elif ...).  My example only eliminated a single level of
artificial indentation.  But my example did have the advantage of
being taken verbatim from actual, working code ;-)


More information about the Python-Dev mailing list