restriction on sum: intentional bug?

Tim Chase python.list at tim.thechases.com
Fri Oct 16 12:59:40 EDT 2009


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








More information about the Python-list mailing list