Feature suggestion: sum() ought to use a compensated summation algorithm

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon May 5 23:43:12 EDT 2008


En Mon, 05 May 2008 11:08:02 -0300, Szabolcs <szhorvat at gmail.com> escribió:

> On May 5, 12:24 pm, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
>> Szabolcs <szhor... at gmail.com> wrote:
>> > On May 5, 9:37 am, Szabolcs Horvát <szhor... at gmail.com> wrote:
>> >> Gabriel Genellina wrote:
>>
>> >> > Python doesn't require __add__ to be associative, so this should
>> >> > not be
>> > used as a general sum replacement.
>>
>> >> It does not _require_ this, but using an __add__ that is not
>> >> commutative and associative, or has side effects, would qualify as a
>> >> serious misuse, anyway.
>>
>> > Sorry, I meant associative only, not commutative.
>>
>> Unfortunately an __add__ which is not associative is actually perfectly
>> reasonable.
>
> Well, 'reasonable' is a subjective notion in this case :-)  I have
> never seen a non-associative use of the plus sign in maths, so I would
> tend to take associativity for granted when seeing a + b + c in code,
> therefore I would avoid such uses.  (Multiplication signs are a
> different story.)  Of course others may feel differently about this,
> and technically there's nothing in the way of using a non-associative
> __add__! :)

You're approaching Python from a mathematical point of view, I presume?
Python has a perfectly defined meaning for a + b + c: simply, expressions  
are evaluated from left to right  
<http://docs.python.org/ref/evalorder.html>.
a+b+c is the same as (a+b)+c and *not* the same thing as a+(b+c).  
Parenthesis aren't required in the first case, not because addition is  
associative, but because evaluation order is clearly defined.
__add__, __mul__ and all other special methods can be used (and in fact,  
*are* used) for many kind of objects, not just numbers; the Tree example  
by Duncan Booth is a perfectly valid application. (Of course this usage  
can be abused, as any other feature, but it's not so common)

-- 
Gabriel Genellina




More information about the Python-list mailing list