[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Python-Dev] Examples for PEP 572

Forwarding the reply to the list. Accidentally pressed the wrong button and
sent this message personally to Serhiy. Sorry :)

??, 4 ???. 2018 ?. ? 11:57, Serhiy Storchaka <storchaka at gmail.com>:

> > 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)
> I was going to rewrite this code as
>      reductor = dispatch_table.get(cls)
>      if reductor:
>          rv = reductor(x)
>      else:
>          rv = x.__reduce_ex__(4)
> There were reasons for the current complex code in Python 2, but now
> classic classes are gone, and every class has the __reduce_ex__ method
> which by default calls __reduce__ which by default is inherited from
> object. With that simplification the benefit of using ":=" in this
> example looks less impressed.
Yes you are right with this particular snippet (in its current version, it
is an echo from Python 2). But I think you have missed the general idea:
The logic of this code is flat (like a switch) but the visual structure is
pretty nested. That is why (maybe just for me) there is a mental imbalance
in perception. And this type of code is rather common. Therefore, for me,
the main gain from using the assignment expression in these patterns of
code is that the visual syntax emphasizes the semantics. To be honest, I do
not see any benefit of usage of assignment expression outside `if` and
`while` headers, but if others do see let it be so.

With kind regards,
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20180704/5ff45c57/attachment-0001.html>