restriction on sum: intentional bug?

Ethan Furman ethan at stoneleaf.us
Fri Oct 16 14:44:59 EDT 2009


Jon Clements wrote:
> On Oct 16, 5:59 pm, Tim Chase <python.l... at tim.thechases.com> wrote:
> 
>>Stephen Hansen wrote:
>>
>>>>Why doesn't duck typing apply to `sum`?
>>
>>>Because it would be so hideously slow and inefficient that it'd be way too
>>>easy a way for people to program something they think should work fine but
>>>really doesn't... alternatively, the function would have to do two
>>>/completely/ different implementations based on what you're passing in, and
>>>that violates duck typing too :)
>>
>>But that's the issue...supporting strings does NOT involve "two
>>/completely/ different implementations based on what you're
>>passing in" but rather just a reduction of starting point
>>(whether 0 or '') and an object that had an __add__ method.
>>String meet these requirements.  Specifically disqualifying
>>strings is where you get the two code-paths/implementations.
>>
>>So I agree with Alan & Peter that this creates an unfortunate
>>language wart among (as Peter aptly puts it) "consenting adults".
>>  I'd feel similarly if certain classes anomalously prevented
>>access to internal "private" data.  We know that if we go mucking
>>around like this, it's our own fault if things break or get slow.
>>  Is Python going to prevent me from typing
>>
>>   count = 0
>>   for i in range(1000000):
>>     if i % 1000: count += 1
>>
>>instead of specifying the step-size?  Or even forcing me to
>>precompute this constant value for `count` because looping is
>>inefficient in this case?
>>
>>Even more annoyingly, sum() *knows the right thing to do* to the
>>degree that it even puts it in the error message...INSTEAD OF
>>JUST FREAKIN' DOING THE RIGHT THING.  Do it inefficiently, or do
>>it efficiently, but it's NOT AN ERROR. (IMHO ;-)
>></soapbox>
>>
>>-tkc
> 
> 
> Does it know the right thing to do though?
> 
> For instance, sum(['1', '2', '3']); it's not completely unreasonable
> for someone to expect
> a result of 6.

It is in Python.  '1' + '2' + '3' == '123', and so should sum.

If sum already has two code branches to handle strings, let the string 
branch do a join.  That's my vote, anyway.  :)

~Ethan~



More information about the Python-list mailing list