Recently I was participating in a thread where -on a side line- the sum function was discussed:
I was wondering (again) why sum does not allow a string as the start value of sum.
Obviously, the current implementation is that that raises a TypeError with a suggestion to use join instead.
I have looked at the discussion here https://bugs.python.org/issue18305 and find there, of course, the performance issue. But what if we would just delegate sum to join in case of a string as the start value.
The only problem might be then if we use a class that is inherited from str and that class has overridden the
__add__ method. Well, that can be easily solved by checking whether this start variable uses the
str.__add__ method or not.
So, in pseudocode, I propose:
def sum(iterable, start=0): if isinstance(start, str) and start.__add__ == str.__add__: return start + "".join(iterable) return orgsum(iterable, start) # orgsum is like current sum without a TypeError for str's.
If we would implement sum like that we don’t need a TypeError when strings are used as start value and there is no need for a performance warning because it will just perform as quick as join.
I think, in all the discussions, nobody has ever come up with this implementation.
Therefore, I would like to propose a PEP for this. Is there a core developer willing and able to help me with that?