[Python-Dev] performance of {} versus dict()

Stephen J. Turnbull stephen at xemacs.org
Thu Nov 15 04:48:22 CET 2012


Chris Angelico writes:
 > On Thu, Nov 15, 2012 at 1:28 PM, Stephen J. Turnbull <stephen at xemacs.org> wrote:
 > > Chris Angelico writes:
 > >
 > >  > >>> {"a":1}+{"b":2}
 > >
 > >  > It would make sense for this to result in {"a":1,"b":2}.
 > >
 > > The test is not "does this sometimes make sense?"  It's "does this
 > > ever result in nonsense, and if so, do we care?"
 > >
 > > Here, addition is usually commutative.  Should {'a':1}+{'a':2} be the
 > > same as, or different from, {'a':2}+{'a':1}, or should it be an error?
 > 
 > >>> "a"+"b"
 > 'ab'
 > >>> "b"+"a"
 > 'ba'
 > 
 > I would say that the two dictionary examples are equally allowed to
 > give different results - that they should be equivalent to (shallow)
 > copy followed by update(), but possibly more efficiently.

I wouldn't.  A string is a sequence of uninterpreted letters, and
necessarily ordered.  In fact, that's about all you can say about
strings in general.  I would prefer that concatenation be expressed by
juxtaposition, but that's troublesome for machine parsing (especially
error recovery).  My intuition is elastic enough to admit exceptional
cases where the essential ordered nature of the objects being "added"
is more important than the customary interpretation of the operator
symbol, so interpreting string addition as concatenation doesn't
bother me.  Furthermore, in string addition both operands affect the
result in proportion to their content, though differently.

Dictionaries aren't ordered, and their "elements" have structure
(key-value pairs).  It would definitely bother me if dictionary
addition weren't commutative, and it's worse that an operand affects
the outcome in an all-or-nothing way.

Also, "update" is more appropriately expressed by an extended
assignment operator.  Defining "+" in terms of "+=" as you propose
just doesn't seem right to me.



More information about the Python-Dev mailing list