On 2021-06-17 00:57, Chris Angelico wrote:
On Thu, Jun 17, 2021 at 9:46 AM Oliver Margetts
<oliver.marge...@gmail.com> wrote:
> I'm not sure why it doesn't special-case it to "".join()
One reason might be because you'd have to read the entire iterator to know if
it really was only strings. So there are concerns with generators which
complicate things a fair bit
Perhaps, but I'm not sure what's actually being verified here. The
check is applied to the start parameter. (If you don't set start,
you'll get a TypeError for trying to add an int and a str.) In fact,
if you disrupt that check, sum() is quite happy to add strings
together - with potentially quadratic runtime:
class AdditiveIdentity:
... def __add__(self, other): return other
...
sum(["Hello ", "world!"], start=AdditiveIdentity())
'Hello world!'
Either way, if there's a non-str part way through, it'll bomb when it
reaches that. I've no idea what the reason is for not bouncing it
straight into join(), but I'm sure there must be one.
I wonder whether we could introduce a new dunder __sum__ for summing
sequences. It would call type(start).__sum__ with the start value and
the sequence.
str.__sum__ would use str.join and list.__sum__ would use list.extend.
The fallback would be to do what it does currently.
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/python-ideas@python.org/message/KANNLLDGJ2ASZVVZEPL5XUZKJJEBVAGG/
Code of Conduct: http://python.org/psf/codeofconduct/