[Python-ideas] Why does `sum` use a default for the `start`parameter?

Terry Reedy tjreedy at udel.edu
Sun Dec 6 01:57:38 CET 2009


Raymond Hettinger wrote:
> 
>>>>> > I prefer (b). The problem with requiring `start` for sequences of 
>>>>> non-
>>>> numerical
>>>>> > objects is that you now have to go out and create a "zero object" 
>>>>> of the
>>>> same
>>>>> > type as your other objects. The object class might not even have 
>>>>> a concept
>>>> of a
>>>>> > "zero object".
>>>>> >
>>>>> If the objects can be summed, shouldn't there also be a zero object?
> 
> 
> Use a single univeral zero object that works for everything.
> Here's an example from my earlier post:
> 
>>>> class Zero:
> ...     'universal zero for addition'
> ...     def __add__(self, other):
> ...         return other
> ...     def __radd__(self, other):
> ...         return other
> ...
>>>> Zero() + 'xyz'
> 'xyz'
>>>> sum(['xyz', 'pdq'], Zero())
> 'xyzpdq'

I would not have expected this to work, as it does not match "The 
iterable‘s items are normally numbers, and are not allowed to be strings."

It appears that it is the start value that may not be a string.
I suggest a doc fix in
http://bugs.python.org/issue7447

FWIW, sum was designed for summing numbers at C speed. I think it 
probably is as good a compromise as we can get. It is easy to program 
any other exact behavior one wants, and summing user objects is going to 
go at Python speed anyway. Certainly, none of the suggested alterations 
strike me as worth breaking code.

Terry Jan Reedy





More information about the Python-ideas mailing list