Re:Examples of Incorrect Abstractions in Other Languages
by throwaway_pdp09 on Wednesday May 20, 2020 @11:45AM
(#23248249)
Like you, I know the O(n^2) bahaviour that would occur with a naive repeated concatenation, and like you I would know how to deal with it. You'd use "".join(...) for the special case it was strings and therefore so would I. This needn't be a footgun of any sort, and don't assume I (or others) are ignorant.
Perhaps not stupid, but ignorant, and not just of the special casing in sum which exist because of a footgun.
sum is basically a readability alternative for functools.reduce for adding numbers, and it's special cased for strings because though it would superficially work for strings otherwise, the performance of repeated string concatenations is pathological in python (as in many garbage-collected languages where it forces many allocations), so a special cases was added which points people to the method to produce exactly the same result without the pathological performance issue.
If you are doing something more complex than numbers with heterogenous data that includes strings in a reduction by the addition operator so that the join you'd use with homogeneous collections of strings isn't what you want (I'm not sure that hypothetical is ever going to happen), use functools.reduce, which for readability you probably should be using in preference to sum() if you aren't doing a mathematical sum anyway.