Technically, in Python, one would expect that that anything which has the __add__
method implemented should be able to use the sum
function.
Strings have __add__
implemented as concatenation:
"abc "+"def"
> 'abc def'
sum
takes a start value as second argument which by default is the int 0
as can be seen by:
sum([])
0
sum([], 7)
7
That is why doing sum(["abc", "def"])
doesn't work, because it tries to add 0
to "abc":
sum(["abc", "def"])
TypeError: unsupported operand type(s) for +: 'int' and 'str'
But giving a string as the start value of sum
, it should work. But it doesn't work, because in the implementation of sum
, there is an ad hoc check to see if the start value is a string (or other unwanted types) and it raises a type error if the start value is a string:
sum(["sf", "34", "342"], "")
TypeError: sum() can't sum strings [use ''.join(seq) instead]
Why does Python go through the trouble of implementing hand-crafted exceptions on certain types in sum
? The simpler, more pythonic way would be for sum to work with anything that has an implementation of __add__
, no?
One can see that without this check sum
would work with strings by defining a "zero" class which when added to anything returns the other thing. If we use that as the starting element, then it bypasses the check (because it is not a string) and sum can be used to add strings:
sum(["a", "b", "c"], type("_", (), {"__add__": lambda _, o: o})())
'abc'