[Python-ideas] PEP: Dict addition and subtraction
Jonathan Fine
jfine2358 at gmail.com
Fri Mar 22 04:36:12 EDT 2019
Python fits well in the mind, because (1) by design it reduces
cognitive load, and (2) it encourages its users to reduce cognitive
load, and (3) we have a culture of reading code, taking pride in our
code. Readability counts.
https://en.wikipedia.org/wiki/Cognitive_load
Steven D'Aprano says that examples such as below don't help us discuss
the cognitive load associated with dict + dict.
> 1. Toy examples using generic names don't count.
> eggs += spam
I assume he's referring to my example
>>> items.update(points)
>>> items += points
In this example, items.update gives useful additional information.
We expect, from duck typing and sensible naming, that points can be
iterated to give key value pairs. In Python, when
>>> a + b
gives one of
TypeError: unsupported operand type(s) for +: 'int' and 'str'
TypeError: Can't convert 'int' object to str implicitly
we get a very strong hint to write instead something like
a + int(b)
str(a) + b
so that the nature of the addition is made clear to the next person
who reads the code (who might be ourselve, in a crisis, in ten years
time.)
(JavaScript does implicit conversion. This makes the code easier to
write, harder to read, and harder to maintain.)
For certain values of dct and lst we get
>>> lst += dct
>>> lst
[('a', 1), ('b', 2), 'c', 'd']
For the same values of dct and lst (if proposal allowed)
>>> dct += lst
>>> dct
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
In these examples, dct is a dict, and lst is a list. This behaviour is
something Python users will have to learn, and have in their mind,
whenever they see '+=' in unfamiliar code.
I find this as much an unwelcome cognitive load as that produced by Javascript's
> 2 * "8"
16
> 2 + "8"
"28"
To be fair, this may in part be a problem with our expectations about +=.
--
Jonathan
More information about the Python-ideas
mailing list