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

Tim Peters tim.peters at gmail.com
Thu Apr 26 12:58:32 EDT 2018


[Kirill Balunov <kirillbalunov at gmail.com>]
> 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.
>
> With kind regards,
> -gdg

Thanks for sharing that!  While nobody else seems to, I absolutely
love real code ;-)

This is effectively an instance of Guido's "if/elif/elif/elif/..."
example template, where binding expressions shine.  But actual real
code can make a point viscerally that "consider stuff akin to the
following semi-abstract pattern" can't.


More information about the Python-Dev mailing list