
Donald Stufft writes:
Python often gets little improvements that on their own are not major enhancements but when looked at cumulatively they add up to a nicer to use language. An example would be set literals, set(["a", "b"]) wasn't confusing nor was it particularly hard to use, however being able to type {"a", "b"} is nice, slightly easier, and just makes the language jsut a little bit better.
Yes, yes, and yes.
Similarly doing:
new_dict = dict1.copy() new_dict.update(dict2)
Isn't confusing or particularly hard to use, however being able to type that as new_dict = dict1 + dict2 is more succinct, cleaner, and just a little bit nicer.
Yes, no, and no. Succint? Yes. Just count characters or lines (but both are deprecated practices in juding Python style). Cleaner? No. The syntax is cleaner (way fewer explicit operations), but the semantics are muddier for me. At one time or another, at least four different interpretations of "dict addition" have been proposed already: 1. item of left operand wins Ie, "add new keys and their values". This is the one I think of as "add", and it's most analogous to the obvious algorithm for "add-as-in-union" for sets. 2. item of right operand wins Ie, "add new values, inserting new keys as needed". I think of this as "update", its per-item semantics is "replace", but it seems to be the favorite for getting "+" syntax. Eh? 3. keywise addition This is collections.Counter, although there are several plausible treatments of missing values (error, additive identity). 4. keys duplication is an error Strictly speaking nobody has proposed this, but it is implicit in many of the posts that give an example of adding dictionaries with no duplicate keys and say, "it's obvious what d1 + d2 should be". Then there's the variant where duplicate keys with the same value is OK. And in the "adding shopping dicts" example you could plausibly argue for two more: 5. keywise max of values So the first person to the refrigerator always has enough eggs to bake her cake, even if nobody else does. 6. keywise min of values If you are walking to the store. Well, maybe those two aren't very plausible.<wink /> Sure, I could internalize any given definition of "dict.__add__", but I probably won't soon. To make my own code readable (including "clearly correct semantics in the application domain") to myself, I'll use .add() and .update() methods, a merged() function, or where there's a domain concept that is more precise, that name. And finally, no. I don't think that's nicer. For me personally, it clearly violates TOOWTDI. For every new user it's definitely "one more thing to learn". And I don't see that the syntax itself is so much nicer than def some_name_that_expresses_domain_semantics(*dicts): new_dict = {} for dict in dicts: new_dict.update(dict) return new_dict new_dict = some_name_that_expresses_domain_semantics(d1, d2, d3) as to justify adding syntax where there is no obvious cross-domain abstraction.