[Python-ideas] Fast sum() for non-numbers

Andrew Barnert abarnert at yahoo.com
Fri Jul 5 07:18:36 CEST 2013


From: Steven D'Aprano <steve at pearwood.info>

Sent: Thursday, July 4, 2013 9:06 PM


> 1) Alex Martelli is, or at least was, against using sum on non-numbers:
> 
> [quote]
> I was responsible for designing sum and doing its first implementation in the 
> Python runtime, and I still wish I had found a way to effectively restrict it to 
> summing numbers (what it's really good at) and block the "attractive 
> nuisance" it offers to people who want to "sum" lists;-). – Alex 
> Martelli Jun 4 '09 at 21:07
> [end quote]

I don't know if I agree with Alex Martelli that this would be a good idea, but… if it is, there's a really easy way to do it. Just check the start parameter (if a non-default value is passed).

After all, if the start value is numeric or not a sequence or whatever the rule is, presumably anything that can be added to it is also numeric enough to be summable. (If you really want to sneak in a start value that passes as numeric but knows how to add itself to a tuple and return a tuple, go for it.)

We already have three checks for the builtin string types (Python/bltinmodule.c:1950); adding a PySequence_Check(start) or PyNumber_Add(zero, start) or the C equivalent of isinstance(start, numbers.Number) or whatever (the details are of course bikesheddable) wouldn't hurt performance. (In fact, because the three string checks only need to be done if the one is-numeric or is-not-sequence or whatever fails, it might even speed things up—but either way, not enough to matter.)



More information about the Python-ideas mailing list