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

Andrew Barnert abarnert at yahoo.com
Sun Feb 15 01:42:50 CET 2015


I'm +1 on constructor, +0.5 on a function (whether it's called updated or merged, whether it's in builtins or collections), +0.5 on both constructor and function, -0.5 on a method, and -1 on an operator.

Unless someone is seriously championing PEP 448 for 3.5, in which case I'm -0.5 on anything, because it looks like PEP 448 would already give us one obvious way to do it, and none of the alternatives are sufficiently nicer than that way to be worth having another.

I agree with everything in Steven's last post about syntax, so I won't repeat it. Additional considerations he didn't mention:

A method or operator raises the same return type issue that set methods return, as soon as you want to extend this beyond dict to other mappings. You're going to need to copy the _from_iterable classmethod documented only in the constructor idea, which is ugly--and it won't work as well in Mapping as in Set, because there are a ton of non-compliant mappings already in the wild, and it's not even clear how some of them _should_ work.

A constructor not only makes the type even more obvious and explicit, it also answers the implementation problem: the only code that has to know about the constructor's signature is the constructor itself, which isn't a problem. Even for weird cases like defaultdict.

A function also avoids the problem, if not quite as nicely. If sorted and reversed return whatever type they want, not the type you pass in, so why should updated be any different? If you really need it to be a MyMapping, you can do MyMapping(updated(a, b)), with the same verbosity and performance cost as when you have to do MySequence(sorted(t)).

A function has the added advantage that it can be backported trivially for 3.4 and 2.7 code.

In fact, because the constructor is more general and powerful, but the function is more backportable, I don't see much problem adding both.

On Feb 14, 2015, at 9:46, Steven D'Aprano <steve at pearwood.info> wrote:

> I've already explained that of all the options, extending the dict 
> constructor (and update method) to allow multiple arguments seems like 
> the best interface to me. As a second-best, a method or function would 
> be okay too.



More information about the Python-ideas mailing list