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

Ron Adam ron3200 at gmail.com
Fri Jul 12 05:43:05 CEST 2013



On 07/11/2013 07:23 PM, Steven D'Aprano wrote:
> On 11/07/13 23:20, Ron Adam wrote:
>> How do you feel about adding the ability of sum to sum vectors or lists
>> of values to each other?
>>
>> sum([[x1, y1], [x2, y2], ...])  --->  [x1+x2, y1+y2]
>
> What I think of that is that it is not backward compatible and would
> completely break any code relying on sum's current behaviour.

That's what I think too.   ;-)

Although it's possible to extend an API in a backwords copatible ways. 
Adding a new keyword would work.  (Not suggesting that.)


> We're in the middle of a long discussion arguing that a *tiny*, *subtle*
> shift in behaviour of sum is sufficient to disqualify the change, and
> you're suggesting something that completely changes the semantics from list
> concatenation to element-by-element addition. No offence Ron, but have you
> been reading the rest of the thread?

No offence taken.  And as you point out, we can't easily add 
element-by-element addition as long as it also does list concatenation.


> If anyone wants element-by-element addition, then can either define a class
> that does so using the + operator (say, numpy arrays) or they define their
> own function.

I'd rather just use a function and not use the '+'.



> Or try to revive PEP 225:
>
> http://www.python.org/dev/peps/pep-0225/

Interesting.  I can see why it didn't get in.  PEP 225 tries to do too much.


I Was looking in the operator module and notice there are __concat__() and 
concat() methods.  I don't think I've seen them anywhere else.

Maybe we could just add a few new functions to the operator module?   Each 
specialised to only numbers, strings, immutable, and mutable types.  That 
might open the door for them being used in a wider scope while not changing 
too much in the near future.


I sort of wish we could add alias's to oppertor methods.  (In a nice way.)

      @__add__
      def __add_number__(self, other):
         ...

      @__add__
      def __add_list__(self, other):
         ...

      @__add__
      def __concat_strings__(self, other):
         ...

Multi-methods for operators(?)

Where __add__ and '+' would work with all of these, but __add_lists__ would 
work only on lists.  It's pretty much how it works now, but sense they are 
all spelled the same, it can be confusing when you see these used from a 
subclass.

Cheers,
    Ron






































More information about the Python-ideas mailing list