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

Guido van Rossum gvanrossum at gmail.com
Tue Mar 15 16:47:20 CET 2005

On Tue, 15 Mar 2005 22:21:07 +1000, Nick Coghlan <ncoghlan at iinet.net.au> wrote:
> Guido van Rossum wrote:
> > I think the conclusion should be that sum() is sufficiently
> > constrained by backwards compatibility to make "fixing" it impossible
> > before 3.0. But in 3.0 I'd like to fix it so that the 2nd argument is
> > only used for empty lists.
> Two questions about this:
> 1. When omitting the second argument, would supplying an empty list return 0,
> None or raise an exception?

Good question...

> The last seems most reasonable, as otherwise the function is guessing about what
> the programmer wants.

OTOH 0 is more compatible and None is a strong candidate too...

> 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) + ...) 

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!

--Guido van Rossum (home page: http://www.python.org/~guido/)

More information about the Python-Dev mailing list