On 14 August 2014 02:37, Steven D'Aprano <steve@pearwood.info> wrote:
A bit of history, as I remember it: sum() exists because for half of Python's lifetime, people were regularly defining this:
def sum(numbers): return reduce(lambda a, b: a+b, numbers)
so they could easy add up a bunch of numbers:
num_pages = sum([ch.pages() for ch in self.chapters])
sort of thing. Since this was a common need, it was decided to add it to the built-ins. But sum() was never intended to replace str.join or list.extend, let alone even more exotic cases.
Built-in sum is aimed at sequences of numbers, not strings, lists, tuples, or Widgets for that matter. Perhaps giving it a start parameter was a mistake, but it is there and backwards compatibility says it isn't going to be removed. But that doesn't mean that the use of sum() on arbitrary types ought to be *encouraged*, even if it is *allowed*.
Interesting point of history: Adding the sum() builtin is when Alex Martelli was given commit privileges (see http://bugs.python.org/issue724936 - found by putting "builtin sum" into the search field on bugs.python.org) Reviewing that issues, in one of the draft patches, all sequences were banned, but that was changed in order to allow sum() to handle sequences that define __add__ as an element-wise operation (since those won't exhibit the quadratic behaviour). The date of the issue also made it possible to find the thread Alex mentions in the list archives: https://mail.python.org/pipermail/python-dev/2003-April/034767.html And there we find that the original patch *did* automatically delegate to str.join, and after an intial review that expressed some reservations (https://mail.python.org/pipermail/python-dev/2003-April/034825.html), Guido specifically requested changing it to disallow strings: https://mail.python.org/pipermail/python-dev/2003-April/034853.html And Alex agreed: https://mail.python.org/pipermail/python-dev/2003-April/034855.html The idea of a join() builtin was also discussed and rejected in that thread. Regards, Nick. P.S. Note that this kind of thread (which I contributed to myself) is why I'm inclined to insist on a PEP for *any* new builtin these days, even non-controversial ones: so the rationale for the associated design decision is less likely to be rehashed at length more than a decade later. Remembering "there was a PEP for that feature, and it listed this as a rejected design alternative" is relatively easy. Remembering "that idea came up in that thread back in 2003" is much, much, harder :P -- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia