[Python-ideas] Yet another sum function (fractions.sum)

Peter Otten __peter__ at web.de
Mon Aug 19 15:58:45 CEST 2013


Paul Moore wrote:

> On 19 August 2013 11:09, Peter Otten
> <__peter__ at web.de> wrote:
> 
>> If that takes on, and the number of sum implementations grows, maybe
>> there should be a __sum__() special (class) method, and the sum built-in
>> be changed roughly to
>>
>> def sum(items, start=0):
>>     try:
>>         specialized_sum = start.__sum__
>>     except AttributeError:
>>         return ... # current behaviour
>>     return specialized_sum(items, start)
>>
>> sum(items, 0.0) would then automatically profit from the clever
>> optimizations of math.fsum() etc.
>>
> 
> Two points:
> 
> 1. Specialising based on the type of the start parameter probably isn't
> ideal - what you *really* want is to specialise on the type of elements in
> the list 

You'd need another language for that -- or pypyesque magic ;)

> (which is problematic, as lists can contain objects of differing
> types, so you have to consider those cases - maybe dispatch based on the
> first element of the list, who knows?)
> 2. If you do specialise based on start, this can easily be implemented
> using the new single-dispatch generic functions (you'd have to make start
> the first argument, but if you're dispatching on it, you'd likely need it
> to be mandatory anyway so that's not such a big deal).
> 
> I'm not sure this is a good idea in any case, though - why is sum(items,
> 0.0) (with a "magic" start parameter which is a float) better than an
> explicit fsum(items) (where the function name says it's a float sum)?

If there are multiple sum functions, typically one per type of summand, how 
can you make them easily discoverable? I doubt that fsum is used in many 
places where it would be appropriate. If you make the optimizations 
available via the built-in sum() you can add a sentence like

"If you provide an explicit start value sum() may pick an algorithm 
optimized for that type." # needs work

to its documentation and be done.



More information about the Python-ideas mailing list