restriction on sum: intentional bug?
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Mon Oct 19 22:42:04 EDT 2009
En Sun, 18 Oct 2009 21:50:55 -0300, Carl Banks <pavlovevidence at gmail.com>
escribió:
> Consider this thought experiment:
>
>
> class Something(object):
> def __radd__(self,other):
> return other + "q"
>
> x = ["a","b","c",Something()]
>
>
> If x were passed to "".join(), it would throw an exception; but if
> passed to a sum() without any special casing, it would successfully
> return "abcq".
>
> Thus there is divergence in the two behaviors, thus transparently
> calling "".join() to perform the summation is a Bad Thing Indeed, a
> much worse special-case behavior than throwing an exception.
Just for completeness, and in case anyone would like to try this O(n²)
process, sum(x) may be rewritten as:
x = ["a","b","c",Something()]
print reduce(operator.add, x)
which does exactly the same thing, with the same quadratic behavior as
sum(), but prints "abcq" as expected.
--
Gabriel Genellina
More information about the Python-list
mailing list