[Python-Dev] Rationale for sum()'s design?

Tim Peters tim.peters at gmail.com
Wed Mar 16 03:23:47 CET 2005

[Alex Martelli]
> I'm reasonably often using sum on lists of datetime.timedelta
> instances, "durations", which ARE summable just like numbers even
> though they aren't numbers.  I believe everything else for which I've
> used sum in production code DOES come under the general concept of
> "numbers", in particular X+0 == X.  Unfortunately, this equation
> doesn't hold when X is a tiwmedelta, as X+0 raises an exception then.

I count timedeltas "as numbers" too -- or at least I did when sum()
was being designed, cuz I asked for the optional start= argument, and
precisely in order to sum things like this (timedelta was indeed the
driving example at the time).

I can't say it bothers me to specify an appropriate identity element
when 0 is inappropriate.  If it switched to ignoring the start=
argument unless the sequence was empty, that would be OK too, although
I think

    sum(seq, start=0)  same-as  start + seq[0] + seq[1] + ...

will always be easiest to explain, so all else being equal I prefer
current behavior.

The number of times I've passed a sequence to sum() with elements that
were lists, tuples, or any other kind of object with a "concatenate"
meaning for __add__ is zero so far.

More information about the Python-Dev mailing list