[Python-ideas] Fast sum() for non-numbers

Ron Adam ron3200 at gmail.com
Sun Jul 7 04:14:54 CEST 2013



On 07/06/2013 04:41 PM, Joshua Landau wrote:
> On 6 July 2013 21:17, Mathias Panzenböck<grosser.meister.morti at gmx.net>  wrote:
>> >After all, what does addition in the context of lists even mean?
> What it currently does.
>
> What is everyone so confused about?

They aren't confused.  It just isn't a clear cut issue.


Ideally...  And being "ideal' isn't practical in this case because it will 
need too many changes.


Take the following example.

        def add_to_values(vs, v):
            return [n + v for n in vs]

Now what do you suppose this should do?

Well it it depends on what vs and v are.  It might add a value to each item 
in a list of values, it might add a value to each byte in a bytes string, 
it might concatenate a string to each string in a list,  or it might join a 
sequence to each sequence in a list.  Sounds reasonable doesn't it?

Now consider that in some companies, programmers are required to take great 
care to be sure that the routines that they write can't do the wrong thing 
with lots of testing to back that up.

That simple routine "ideally" should be dead simple, but now it requires 
some added care to be sure it can't do the wrong thing.  Which could also 
slow it down.  :/

Generalised routines are very nice and can save a lot of work, but it is 
easier to add behaviours than it is to limit unwanted behaviours.  The 
problem here is that the different behaviours use a similar operator at a 
very low level.

But, can we change this?  Probably not any time soon.  It would mean 
changing __add__, __iadd__, __mul__, __rmul__, __imul__, and possibly a few 
others for a lot of different objects to get a clean separation of the 
behaviours.  And we would need new symbols and method names to replace those.

So the question becomes how we be more specific in a case like this and 
avoid the extra conditional expression.  This is one way...

 >>> def add_value_to_many(value, many):
...         return [int.__add__(x, value) for x in many]
...
 >>> add_value_to_many(4, [3, 6, 0])
[7, 10, 4]
 >>> add_value_to_many("abc", "efg")
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "<stdin>", line 2, in add_value_to_many
   File "<stdin>", line 2, in <listcomp>
TypeError: descriptor '__add__' requires a 'int' object but received a 'str'

It rejects the unwanted cases without the test.  But different operators 
would have been a bit nicer.

Cheers,
     Ron























More information about the Python-ideas mailing list