Augmented assignment (was RE: Why should I switch to Python?)

Tim Peters tim_one at
Sat May 13 08:21:57 CEST 2000

[Tim, in praise of += and its happy little friends]

[Grant Griffin]
> Forgive me, Tim,

It takes much more than that to buy my forgiveness -- but then it takes much
more than the rest to incur my implacable wrath <wink>.

> but as a Python newbie, I had inferred that part of Python's design
> philosophy was to minimize redundant constructs, to encourage regularity
> in Python code.  Likewise, another design philosophy I had inferred
> was to minimize "hyroglyphics" (tm), to make the language easy to learn
> and read; the aforementioned operators definity contribute to C's distinct
> "gobbledygook" look to the uninitiated.  My beloved '+=' (and friends)
> fail on both these counts.
> ...

The syntactic case for augmented assignment is marginal, although the
Pythonic Thesis "readability counts" certainly applies to

    long_name[indirect_index1[i], indirect_index2[j]] += 3

vs the current alternative.  "+=" is easy to learn, and easy to read once
learned -- Python is designed for people, not chimpanzees <wink -- but let's
give users some credit here!  this just isn't hard>.  Python has a long &
unbroken history of adding more "mere syntactic sugar" with each release,
and I don't think any addition of that nature has been regretted, except for
the extent to which "lambda" snuck in on that basis.

The much stronger case is semantic, though:  Python supports operator
overloading, and e.g. when you're slinging multi-megabyte arrays in NumPy,

    x = x + y  # add matrix x to matrix y elementwise, storing back into x

can be an efficiency disaster.  Just as in C++, providing a fundamentally
*different method* for "+=" than for "+" can be a huge win.  To be a little
more concrete while remaining totally inaccurate <wink>, the Matrix author
would love to define Matrix.__add__ to return a new object, but
Matrix.__addeq__ to modify its first ("self") argument in-place.  The last
design Guido sketched for this would allow each class author to make the
"mutate or create?" choice for themself.

There's no obvious way to get the effect of in-place

    x += y

today, short of using x.add_in_place(y) notation, and the latter is a lot
less readable in several natural domains.

    to-do-can-always-be-rationalized<wink>-ly y'rs  - tim

More information about the Python-list mailing list