[Python-ideas] Yet another sum function (fractions.sum)
Peter Otten
__peter__ at web.de
Mon Aug 19 12:09:49 CEST 2013
Oscar Benjamin wrote:
> The discussion around having a sum() function in the statistics module
> reminded me that despite the fact that there are two functions in the
> stdlib (and more in the third-party libraries I use) I have previously
> rolled my own sum() function. The reason is that the stdlib does not
> currently contain a function that can sum Fractions in linear time for
> many inputs even though it is possible to implement a function that
> achieves closer to linear performance in more cases. I propose that
> there could be a sum() function or class-method in the fractions
> module for this purpose. I would just raise this on the tracker but
> seeing how many feathers were ruffled by statistics.sum I thought I'd
> suggest it here first.
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.
More information about the Python-ideas
mailing list