# [Python-ideas] Current use of addition in Python

Jonathan Fine jfine2358 at gmail.com
Mon Mar 4 09:03:38 EST 2019

```Summary: This thread is for recording current use of addition in
Python. This post covers the built-in types. I'll do Counter and
numpy.array in another post. Please use another thread to discuss
possible possible future use of addition.

BACKGROUND
At present constructions such as
{'a': 1} + {'b': 2}
produce
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'

Elsewhere on this list, we're discussing whether to extend dict so
that it supports such constructions, and if so what semantics to give
to addition of dictionaries.

In this thread I intend to record the CURRENT use of addition in
Python, in a neutral manner. (However, I will focus on what might be
called the mathematical properties of addition in Python.)

BUILT-IN TYPES
In this post I talk about the exiting built-in types: see
https://docs.python.org/3/library/stdtypes.html

The NUMERIC types support addition, which has the following properties

Commutative: a + b == b + a
Associative: (a + b) + c == a + (b + c)
Left-cancellation: if (a + b) == (a + c): assert b == c
Right-cancellation: if (a + b) == (c + b): assert a == c
Existence of zero (depending on type): zero + a == a + zero == a
Multiplication by non-negative integer: a + a + .... + a == a * n == n * a

Note: For floats, the equalities are ideal. For example, sometimes
huge + tiny == huge + zero
and so we don't exactly have cancellation.

The SEQUENCE types (except range) have the following properties

Associative
Left-cancellation
Right-cancellation
Existence of zero
Multiplication by non-negative integer.

Note: Even though range is a sequence type, range(3) + range(3) produces
TypeError: unsupported operand type(s) for +: 'range' and 'range'

By the way, although documented, I find this a bit surprising:
>>> (0, 1, 2) * (-1) == ()
True
I'd have expected a ValueError. As things stand
seq * (-1) * (-1)
is not associative. And
(-1) * seq == -seq
is not true, although the left hand side is defined.

CONCLUSION
I've recorded the behaviour of addition for the built-in types. I'll
do Counter and numpy.array in another post, later today. Please use
another thread to discuss possible future use of addition. My aim in
this thread is to establish and record the present use, to better
support discussion of future use.

--
Jonathan
```

More information about the Python-ideas mailing list