[Python-ideas] Dict joining using + and +=

INADA Naoki songofacandy at gmail.com
Fri Mar 1 08:19:34 EST 2019


On Fri, Mar 1, 2019 at 10:10 PM Steven D'Aprano <steve at pearwood.info> wrote:
>
> On Fri, Mar 01, 2019 at 08:59:45PM +0900, INADA Naoki wrote:
> > I dislike adding more operator overload to builtin types.
> >
> > str is not commutative, but it satisfies a in (a+b), and b in (a+b).
> > There are no loss.
>
> Is this an invariant you expect to apply for other classes that support
> the addition operator?
>
>     5 in (5 + 6)

I meant more high level semantics: "no loss".  Not only "in".
So my example about set used "<=" operator.

5 + 6 is sum of 5 and 6.

>
>     [1, 2, 3] in ([1, 2, 3] + [4, 5, 6])
>

Both of [1,2,3] and [4,5,6] are not lost in result.

>
> Since it doesn't apply for int, float, complex, list or tuple, why do
> you think it must apply to dicts?
>

You misunderstood my "no loss" expectation.


>
> > In case of dict + dict, it not only sum.  There may be loss value.
>
> Yes? Why is that a problem?
>

It's enough reason to I dislike.

>
> >    {"a":1} + {"a":2} = ?
>
> Would you like to argue that Counter.__add__ is a mistake for the same
> reason?
>

In Counter's case, it's clear.  In case of dict, it's unclear.

>     Counter(('a', 1)) + Counter(('a', 2)) = ?
>
>
> For the record, what I expected the above to do turned out to be
> *completely wrong* when I tried it. I expected Counter({'a': 3}) but the
> actual results are Counter({'a': 2, 1: 1, 2: 1}).

It just because you misunderstood Counter's initializer argument.
It's not relating to how overload + or | operator.

>
> Every operation is going to be mysterious if you have never
> learned what it does:
>
>     from array import array
>     a = array('i', [1, 2, 3])
>     b = array('i', [10, 20, 30])
>     a + b = ?
>
> Without trying it or reading the docs, should that be an
> error, or concatenation, or element-wise addition?
>

I never say every operator must be expected by everyone.
Don't straw man.


-- 
INADA Naoki  <songofacandy at gmail.com>


More information about the Python-ideas mailing list