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

M.-A. Lemburg mal at egenix.com
Thu Feb 12 09:51:22 CET 2015


On 12.02.2015 04:59, Chris Angelico wrote:
> On Thu, Feb 12, 2015 at 2:24 PM, Skip Montanaro
> <skip.montanaro at gmail.com> wrote:
>> Addition in the usual sense of the word wouldn't be commutative for
>> dictionaries. In particular, it's hard to see how you could define addition
>> so these two expressions are equal:
>>
>> {'a': 1} + {'a': 2}
>>
>> {'a': 2} + {'a': 1}
>>
>> '+=' is no problem.
> 
> Does it have to be? It isn't commutative for strings or tuples either.
> Addition of complex objects does at times depend on order (though as
> we saw in another thread, it can be very confusing if the _type_ can
> change if you switch the operands), so I would have no problem with
> the right-hand operand "winning" when there's a key collision.

Solving that is simple: you define key collisions as having an
undefined result. Then '+' for dicts is commutative.

However, I don't really see the point in having an operation that
takes two dictionaries, creates a new empty one and updates this
with both sides of the operand. It may be theoretically useful,
but it results in the same poor performance you have in string
concatenation.

In applications, you normally just need the update functionality
for dictionaries. If you do need a copy, you can create a copy
explicitly - but those cases are usually rare.

So +1 on the '+=' syntax, -1 on '+' for dicts.

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Feb 12 2015)
>>> Python Projects, Coaching and Consulting ...  http://www.egenix.com/
>>> mxODBC Plone/Zope Database Adapter ...       http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...        http://python.egenix.com/
________________________________________________________________________

::::: Try our mxODBC.Connect Python Database Interface for free ! ::::::

   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
    D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
           Registered at Amtsgericht Duesseldorf: HRB 46611
               http://www.egenix.com/company/contact/


More information about the Python-ideas mailing list