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

Steven D'Aprano steve at pearwood.info
Fri Feb 13 07:56:35 CET 2015


On Thu, Feb 12, 2015 at 08:22:01PM -0800, Chris Barker wrote:
> On Thu, Feb 12, 2015 at 6:45 PM, Steven D'Aprano <steve at pearwood.info>
> wrote:
> 
> > - dict(a,b,c,d) takes 6 characters more to write than a+b+c+d.
> >
> 
> and dict(a,b)
> 
> is three times as many characters as:
> 
> a + b
> 
> - just sayin'

And the difference between:

    default_settings + global_settings + user_settings

versus:

    dict(default_settings, global_settings, user_settings)

is only four characters. If you're using a, b, c as variable names in 
production, you probably have bigger problems than an extra four 
characters :-)


> I'm curious what the aversion is to having an operator -- sure, it's not a
> big deal, but then again there's very little cost, as well. I can't really
> see a "trap" here. Sure there are multiple ways it could be defined, but
> having it act like update() seems pretty explainable.

Each of these in isolation is a little thing, but enough little things 
make a big thing:

Duplicating functionality ("more than one way to do it") is not always 
wrong, but it's a little smelly (as in a code smell, or in this case, an 
API smell).

Some people here find + to be a plausible operator. I don't. I react to 
using + for things which aren't addition in much the same way that I 
expect you would react if I suggested we used ** as the operator. "Why 
on earth would you want to use ** it's nothing like exponentiation!"

As the experience of lists and tuples show, extending a syntax 
originally designed by C programmers to make numeric addition easier 
into non-numeric contests is fraught with odd corner cases, gotchas and 
language warts.

Operator overloading may be a code smell as often as it is a benefit. 
Google for "operator overloading considered harmful".

The + operator is a binary operator, which is a more limited interface 
than function/method calls. You can't write a.update(b, c, d, spam=23) 
using a single + call.

Operators are harder to search for than named functions. Especially + 
which is an operator that has specific meaning to most search engines.

Some languages may be able to optimize a + b + c + d to avoid making and 
throwing away the intermediate dicts, but in general Python cannot. So 
it is going to fall into the same trap as list addition does. While it 
is not common for this to lead to severe performance degradation, when 
it does happen the cost is *so severe* that we should think long and 
hard before adding any more O(N**2) booby traps into the language.



-- 
Steve


More information about the Python-ideas mailing list