[Python-Dev] sum(...) limitation

Julian Taylor jtaylor.debian at googlemail.com
Sat Aug 2 12:11:54 CEST 2014


On 02.08.2014 08:35, Terry Reedy wrote:
> On 8/2/2014 1:57 AM, Allen Li wrote:
>> On Fri, Aug 01, 2014 at 02:51:54PM -0700, Guido van Rossum wrote:
>>> No. We just can't put all possible use cases in the docstring. :-)
>>>
>>>
>>> On Fri, Aug 1, 2014 at 2:48 PM, Andrea Griffini <agriff at tin.it> wrote:
>>>
>>>      help(sum) tells clearly that it should be used to sum numbers
>>> and not
>>>      strings, and with strings actually fails.
>>>
>>>      However sum([[1,2,3],[4],[],[5,6]], []) concatenates the lists.
>>>
>>>      Is this to be considered a bug?
>>
>> Can you explain the rationale behind this design decision?  It seems
>> terribly inconsistent.  Why are only strings explicitly restricted from
>> being sum()ed?  sum() should either ban everything except numbers or
>> accept everything that implements addition (duck typing).
> 
> O(n**2) behavior, ''.join(strings) alternative.
> 
> 

hm could this be a pure python case that would profit from temporary
elision [0]?

lists could declare the tp_can_elide slot and call list.extend on the
temporary during its tp_add slot instead of creating a new temporary.
extend/realloc can avoid the copy if there is free memory available
after the block.

[0] https://mail.python.org/pipermail/python-dev/2014-June/134826.html


More information about the Python-Dev mailing list