Modifying the {} and [] tokens

Hans Nowak hans at zephyrfalcon.org
Sat Aug 23 14:51:17 EDT 2003


Geoff Howland wrote:

> On Sat, 23 Aug 2003 12:40:05 -0400, Roy Smith <roy at panix.com> wrote:
> 
>>Geoff Howland <ghowland at lupineNO.SPAMgames.com> wrote:
>>
>>>{} + {} is not allowed.
>>
>>What would it mean?  What would you do if you had two dicts:
>>
>>d1 = {'a':1, 'b':2}
>>d2 = {'a':42}
>>
>>what would the value of (d1+d2)['a'] be?
> 
> 
> I dont think it matters.  Pick one and make that the standard.

Ah, but I think it matters to Guido, or dict operators like these would have 
been added long ago.

The problem here is that, when looking at d1 + d2, it is not obvious what is 
going on.  If the same key appears in both d1 and d2, what will the resulting 
dict have?  The value in d1?  The value in d2?  Or maybe an exception will be 
raised?  Different people will have different notions here about what is 
"obvious" and "natural".

"Pick one and make that the standard" may work in some other languages, but 
that is usually not how Python's design works.  If there is not "one obvious 
way", chances are it won't make it into the language.  (Of course, there are 
exceptions... but this seems to be a rule-of-thumb.)

Fortunately, you can always roll your own dict with the behavior *you* find 
natural and obvious.  So you can add a + operator to your custom dict, etc. 
However, it is not possible to change the behavior of literals.  They will 
always behave (and be instances of) like the original, built-in object.  As a 
result, you'll be forced to write something like

   d1 = mydict({'a': 1, 'b': 2})
   d2 = mydict({'a': 42})
   d3 = d1 + d2

On a side note, I don't think the other poster was trying to be facetious when 
he suggested you use Ruby... if this language feature is really important to 
you, then maybe Ruby may be a better choice, since that language is more 
"malleable" than Python.

HTH,

-- 
Hans (hans at zephyrfalcon.org)
http://zephyrfalcon.org/







More information about the Python-list mailing list