[Python-ideas] adding dictionaries

Steven D'Aprano steve at pearwood.info
Tue Jul 29 05:34:12 CEST 2014


On Mon, Jul 28, 2014 at 12:17:10PM -0500, Ron Adam wrote:
> 
> On 07/28/2014 11:04 AM, Steven D'Aprano wrote:
[...]

> >new_dict = a + b + c + d
> >
> >Pros: + is short to type; subclasses can control the type of new_dict.
> >Cons: dict addition isn't obvious.
> 
> I think it's more obvious.  It only needs __add__ and __iadd__ methods to 
> make it consistent with the list type.

What I meant was that it wasn't obvious what dict1 + dict2 should do, 
not whether or not the __add__ method exists.

> I think this added consistency between lists and dicts would be useful.

Lists and dicts aren't the same kind of object. I'm not sure it is 
helpful to force them to be consistent. Should list grow an update() 
method to make it consistent with dicts? How about setdefault()?

As for being useful, useful for what? Useful how often? I'm sure that 
one could take any piece of code, no matter how obscure, and say it is 
useful *somewhere* :-) but the question is whether it is useful enough 
to be part of the language.

I was wrong to earlier dismiss the OP's usecase for dict addition by 
suggestion dict(a, **b). Such a thing only works if all the keys of b 
are valid identifiers. But that doesn't mean that just because my 
shoot-from-the-hip response missed the target that we should conclude 
that dict addition solves an important problem or that + is the correct 
way to spell it.

I'm still dubious that it's needed, but if it were, this is what I 
would prefer to see:

* should be a Mapping method, not a top-level function;

* should accept anything the dict constructor accepts, mappings or 
  lists of (key,value) pairs as well as **kwargs;

* my prefered name for this is now "merged" rather than "updated";

* it should return a new mapping, not modify in-place;

* when called from a class, it should behave like a class method: 
  MyMapping.merged(a, b, c) should return an instance of MyMapping;

* but when called from an instance, it should behave like an instance
  method, with self included in the chain of mappings to merge:
  a.merged(b, c) rather than a.merged(a, b, c).


I have a descriptor type which implements the behaviour from the last 
two bullet points, so from a technical standpoint it's not hard to 
implement this. But I can imagine a lot of push-back from the more 
conservative developers about adding a *fourth* method type (even if it 
is private) to the Python builtins, so it would take a really compelling 
use-case to justify adding a new method type and a new dict method.

(Personally, I think this hybrid class/instance method type is far more 
useful than staticmethod, since I've actually used it in production 
code, but staticmethod isn't going away.)


-- 
Steven


More information about the Python-ideas mailing list