sum for sequences?

Alf P. Steinbach alfps at start.no
Thu Mar 25 09:02:05 EDT 2010


* Neil Cerutti:
> On 2010-03-25, Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> wrote:
>>> You might not want to be so glib.  The sum doc sure doesn't
>>> sound like it should work on lists.
>>>
>>>     Returns the sum of a sequence of numbers (NOT strings) plus the
>>>     value of parameter 'start' (which defaults to 0).
>> What part of that suggested to you that sum might not be polymorphic? 
>> Sure, it says numbers (which should be changed, in my opinion), but it 
>> doesn't specify what sort of numbers -- ints, floats, or custom types 
>> that have an __add__ method.
> 
> WTF.

I think Steven's argument is that it would be pointless for 'sum' to distinguish 
between user-defined numerical types and other types that happen to support '+'.

It could make such a distinction since there's a type hierarchy for numbers, but 
then that should IMHO be more clearly documented.

However, given that it isn't restricted to numbers, the restriction wrt. strings 
is a bit perplexing in the context of modern CPython. But for Python 
implementations that don't offer the '+=' optimization it might help to avoid 
gross inefficiencies, namely quadratic time string concatenation. E.g., here's a 
natural implementation of sum  --  with unoptimized '+=' yielding quadratic time 
for the string concatenation (with modern CPython it's linear time, though):

<example>
   >>> def sum_all( values, start = 0 ):
   ...     s = start
   ...     for v in values: s += v
   ...     return s
   ...
   >>> sum_all( (1, 2, 3, 4) )
   10
   >>> sum_all( ("a", "b", "c", "d"), "" )
   'abcd'
   >>> sum_all( ((1, 2), (3, 4), (5, 6)), () )
   (1, 2, 3, 4, 5, 6)
   >>> _
</example>

However, if that hypothesis about the rationale is correct, then 'sum' should 
also be restricted to not handle tuples or lists, so forth, but at least the 
CPython implementation does.

So perhaps the documentation needs to be more clear?


Cheers,

- Alf



More information about the Python-list mailing list