[Python-ideas] PEP: Dict addition and subtraction

David Mertz mertz at gnosis.cx
Thu Mar 21 20:13:01 EDT 2019


On Thu, Mar 21, 2019, 7:48 PM Steven D'Aprano <steve at pearwood.info> wrote:

> A number of people including Antoine and Serhiy seem to have taken the
> position that merely adding dict.__add__ will make existing code using +
> harder to understand, as you will need to consider not just numeric
> addition and concatenation, but also merging, when reading code.
>
> Would you agree that this example of + is perfectly clear today?
>
>     for digit in digits:
>         num = num*10 + digit
>
> By both the naming (digit, num) and presence of multiplication by the
> literal 10, it should be pretty obvious that this is probably doing
> integer addition.
>

Yep. This is clear and will not become less clear if some more objects grow
an .__add__() methods. Already, it is POSSIBLE that `num` and `digit` mean
something other than numbers. Bad naming of variables if so, but not
prohibited.

For example, NumPy uses '+' and '*' for elementwise operations, often with
broadcasting to different areas shapes. Maybe that's code dealing with
vectorised arrays... But probably not.

Holoviews users '+' and '*' to combine elements of graphs. E.g

labelled = low_freq * high_freq * linpoints
overlay + labelled + labelled.Sinusoid.Low_Frequency

ggplot in R has similar behavior. Maybe your loop is composing a complex
graph... But probably not.

Nonetheless, if I see `dict1 + dict2` the meaning you intend in the PEP
does not jump out as the obvious behavior. Nor even as the most useful
behavior. Of course I could learn it and teach it, but it will always feel
like a wart in the language.

In contrast, once you tell me about the special object "vectorised arrays",
`arr1 + arr2` does exactly what is expect in NumPy.

And your subjective feeling is well-noted :-)
>

This is more than "merely subjective." I teach Python. I write books about
Python. I've had tens of millions of readers of articles I've written about
Python. I'm not the only person in this discussion with knowledge of
learners and programmers and scientists... But the opinions I'm expressing
ARE on their behalf too (as I perceive likely surprise and likely bugs).

I like most of the design of Python. Almost all, even. But there are a few
warts in it. This would be a wart.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190321/b8f9c68f/attachment-0001.html>


More information about the Python-ideas mailing list