[Python-ideas] Adding "+" and "+=" operators to dict

Steven D'Aprano steve at pearwood.info
Fri Feb 13 07:19:05 CET 2015


On Thu, Feb 12, 2015 at 07:43:36PM -0800, Chris Barker - NOAA Federal wrote:
> > avoids any confusion over operators and having += duplicating the
> > update method.
> 
> += duplicates the extend method on lists.

Yes it does, and that sometimes causes confusion when people wonder why 
alist += blist is not *quite* the same as alist = alist + blist. It also 
leads to a quite ugly and unfortunate language wart with tuples:

py> t = ([], None)
py> t[0] += [1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
py> t
([1], None)

Try explaining to novices why this is not a bug.


> And it's really redundant for numbers, too:
> 
> x += y
> 
> x = x + y

Blame C for that. C defines so many ways to do more or less the same 
thing (x++ ++x x+=1 x=x+1) that a generation or three of programmers 
have come to consider it normal.


> So plenty of precedent.

Historical accident and backwards compatibility require that certain, 
hmmm, "dirty" is too strong a word, let's say slightly tarnished, design 
choices have to persist forever, or near enough to forever, but that's 
not a good reason for propagating the same choices into new 
functionality.

It is *unfortunate* that += works with lists and tuples because + works, 
not a feature to emulate. Python made the best of a bad deal with 
augmented assignments: a syntax which works fine in C doesn't *quite* 
work cleanly in Python, but demand for it lead to it being supported. 
The consequence is that every generation of Python programmers now need 
to learn for themselves that += on non-numeric types has surprising 
corner cases. Usually the hard way.


> And my experience with newbies (been teaching intro to python for a
> few years) is that they grab onto + for concatenating strings really
> quickly. And I have a hard time getting them to use other methods for
> building up strings.

Right. And that is a *bad thing*. They shouldn't be using + for 
concatenation except for the simplest cases.



-- 
Steve


More information about the Python-ideas mailing list