[Python-Dev] The new and improved PEP 572, same great taste with 75% less complexity!

Larry Hastings larry at hastings.org
Thu Apr 26 14:07:05 EDT 2018



On 04/26/2018 06:27 AM, Kirill Balunov wrote:
> Not sure, but if additional motivating examples are required, there is 
> a common pattern for dynamic attribute lookup (snippet from `copy.py`):
>
>     reductor = dispatch_table.get(cls)
>     if reductor:
>         rv = reductor(x)
>     else:
>         reductor = getattr(x, "__reduce_ex__", None)
>         if reductor:
>             rv = reductor(4)
>         else:
>             reductor = getattr(x, "__reduce__", None)
>             if reductor:
>                 rv = reductor()
>             else:
>                 raise Error("un(shallow)copyable object of type %s" % cls)
>
> which can with the current `binding expression` syntax simplified to:
>
>     if reductor := dispatch_table.get(cls):
>         rv = reductor(x)
>     elif reductor := getattr(x, "__reduce_ex__", None):
>         rv = reductor(4)
>     elif reductor := getattr(x, "__reduce__", None):
>         rv = reductor()
>     else:
>         raise Error("un(shallow)copyable object of type %s" % cls)
>
> which becomes much clearer, at least in my opinion.

I hate to be pedantic--there's enough of that going on in this 
thread--but I can't agree with the word "simplifed" above.  I agree that 
the code using binding expressions is /shorter./  But considering that 
emit the two code examples implement the exact same algorithm, to the 
point where their bytecode would look nearly* identical, ISTM that the 
two code examples are of identical /complexity./

Comparing the two, the code using the binding expressions obviates four 
newlines, three uses of the identifier "reductor", and allows folding 
two "else / if"s into "elif"s.  In exchange, it adds three extra colons, 
and the density of complexity per line has shot up. Whether or not 
that's an improvement is in the eye of the beholder, and I gather the 
battle lines around this PEP have already been clearly drawn.  But it 
cannot be said that this transformation has made the code simpler.

Personally, I've already voted -1; I don't see the version using the 
binding expressions as an improvement.  Expressing the same code using 
slightly fewer characters doesn't justify adding syntax to the language 
in my opinion.


//arry/

* I assume that--if we don't already have one--we'll add a new 
DUP_AND_STORE_FAST opcode for binding expressions.  On the other hand, 
"STORE_FAST n" followed by "LOAD_FAST n" is a common enough bytecode 
idiom that the peephole optimizer could notice it and pretty easily swap 
it for DUP_AND_STORE_FAST.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20180426/93e8aaa7/attachment.html>


More information about the Python-Dev mailing list