restriction on sum: intentional bug?
MRAB
python at mrabarnett.plus.com
Fri Oct 16 12:24:05 EDT 2009
Stephen Hansen wrote:
>
>
> On Fri, Oct 16, 2009 at 8:39 AM, Alan G Isaac <alan.isaac at gmail.com
> <mailto:alan.isaac at gmail.com>> wrote:
>
> I expected this to be fixed in Python 3:
>
> sum(['ab','cd'],'')
>
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: sum() can't sum strings [use ''.join(seq) instead]
>
> Of course it is not a good way to join strings,
> but it should work, should it not? Naturally,
>
> '' + 'ab' + 'cd'
>
> 'abcd'
>
> 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 :)
>
> Duck typing isn't an absolute. Sum's not broken... This is a
> "practicality beats purity" thing; maybe sum should just add up
> everything passed to it and as long as no errors happen, return the
> result. But in practice, if someone passes sequences of strings to it,
> it'd create/destroy so many strings (which is way more expensive then
> just creating and destroying successive integers), people would be
> making really bad code-decisions even when it seems a perfectly valid
> thing to do.
>
It checks to see whether you're trying to sum strings, so it's already
treating them as a special case. Why can't it just use str.join
internally instead in that case instead of raising an exception?
More information about the Python-list
mailing list