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

Paul Moore p.f.moore at gmail.com
Mon Aug 19 12:31:13 CEST 2013


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 (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)?

Paul
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130819/68105d4f/attachment.html>


More information about the Python-ideas mailing list