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

Nick Coghlan ncoghlan at iinet.net.au
Wed Mar 16 13:45:10 CET 2005

Guido van Rossum wrote:
>>2. How would the initial value that forms the basis of summation be built for
>>non-empty sequences?
> Here's you're way off. There's never any use of "+=", so never any
> need to create a new object. The algorithm I had in mind was:
> - if empty, return 2nd arg
> - if one item, return that
> - if more than one item (A, B, C, ...) return (...((A + B) + C) + ...) 

There I go again, missing the obvious and thinking things are more complicated 
than they really are. . .

> But I'm not so sure now. Thinking ahead to generic types, I'd like the
> full signature to be:
>   def sum(seq: sequence[T], initial: T = 0) -> T.
> and that's exactly what it is today. Conclusion: sum() is perfect after all!

So the official verdict is "sum() is mainly intended for numbers, but can be 
used with other types by supplying a default argument"?

I guess that leaves Alex's question of whether or not supplying a string of some 
description as the initial value can be legitimately translated to:

   if isinstance(initial, basestring):
     return initial + type(initial)().join(seq)

rather than raising the current TypeError that suggests the programmer may want 
to rewrite their code.


Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia

More information about the Python-Dev mailing list