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

Nick Coghlan ncoghlan at iinet.net.au
Mon Mar 14 11:20:56 CET 2005


Guido van Rossum wrote:
> But I think the logical consequence of your approach would be that
> sum([]) should raise an exception rather than return 0, which would be
> backwards incompatible. Because if the identity element has a default
> value, the default value should be used exactly as if it were
> specified explicitly.
> 
> Unfortunately my proposal is also backwards incompatible, since
> currently sum([1,1], 40) equals 42.

Somewhat ugly, but backwards compatible:

sentinel = object()
def sum(iterable, initial=sentinel):
   itr = iter(iterable)
   if initial is not sentinel:
     # Initial value provided, so use it
     value = initial
   else:
     try:
       first = itr.next()
     except StopIteration:
       # Empty iterable, return 0 for backwards compatibility
       # Also correct for standard numerical use
       return 0
     # Assume default constructor returns the additive identity
     value = type(first)()
     value += first
   # Add the elements
   for item in itr:
     value += item
   return value

Py> sum([])
0
Py> seq = ([1], [2], [3])
Py> sum(seq)
[1, 2, 3]
Py> seq
([1], [2], [3])
Py> seq = ('1', '2', '3')
Py> sum(seq)
'123'
Py> seq
('1', '2', '3')

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net


More information about the Python-Dev mailing list