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

Georg Brandl g.brandl at gmx.net
Sat Dec 5 18:36:32 CET 2009


Vitor Bosshard schrieb:
> 2009/12/5 George Sakkis <george.sakkis at gmail.com>:
>> On Sat, Dec 5, 2009 at 6:45 PM, Andre Engels <andreengels at gmail.com> wrote:
>>
>>> On Sat, Dec 5, 2009 at 12:55 PM, Ram Rachum <cool-rr at cool-rr.com> wrote:
>>>> I noticed that `sum` tries to add zero to your iterable. Why? Why not just skip
>>>> adding any start value if none is specified?
>>>>
>>>> This current behavior is preventing me from using `sum` to add up a bunch of non-
>>>> number objects.
>>>
>>> In your proposed implementation, sum([]) would be undefined.
>>
>> Which would make it consistent with min/max.
> 
> 
> And in that case the special string handling could also be dropped?
> 
>>>> sum(["a","b"], "start")
> Traceback (most recent call last):
>   File "<pyshell#0>", line 1, in <module>
>     sum(["a","b"], "start")
> TypeError: sum() can't sum strings [use ''.join(seq) instead]
> 
> 
> This behaviour is quite bothersome. Sum can handle arbitrary objects
> in theory (as long as they define the correct special methods, etc.),
> but it gratuitously raises an exception on strings.

This seems to be an instance where the "practicality" Zen rule beats the
"special cases" rule :)

Georg

-- 
Thus spake the Lord: Thou shalt indent with four spaces. No more, no less.
Four shall be the number of spaces thou shalt indent, and the number of thy
indenting shall be four. Eight shalt thou not indent, nor either indent thou
two, excepting that thou then proceed to four. Tabs are right out.




More information about the Python-ideas mailing list