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

Andrew Barnert abarnert at yahoo.com
Sun Jul 7 02:30:40 CEST 2013


On Jul 6, 2013, at 11:54, Joshua Landau <joshua.landau.ws at gmail.com> wrote:

> On 6 July 2013 08:07, Andrew Barnert <abarnert at yahoo.com> wrote:
>> On Jul 5, 2013, at 23:32, Steven D'Aprano <steve at pearwood.info> wrote:
>> 
>>> On 06/07/13 06:25, Terry Reedy wrote:
>>> 
>>>> When Alex said that it was not possible to determine if the start value is a number, he was talking in the context of old style classes where the type of every user class was 'Class' and the type of every user instance was 'Instance' (or something like that). In Python 3, with ABCs, isinstance(start, Number) would solve the problem as long as the requirement were documented.
>>> 
>>> 
>>> For the record, it has always been possible to check if something is a number:
>>> 
>>> 
>>> try:
>>>   x + 0
>>> except TypeError:
>>>   print "x is not a number"
>> 
>> This isn't a very good rule for "is a number". You can add 0 to numpy arrays, for example, and they're not numbers.
>> 
>> But I think it is actually a good rule for "is summable". If you've got something that's not a number, but 0+x makes sense, summing probably also makes sense. Conversely, if you create some type that is numeric, but isn't addable to 0, you wouldn't be surprised if you couldn't sum it.
> 
> Hyelll nooo (imagine I said that with distortedly high pitch while
> wearing a hat).
> 
> What about summing vectors? You can't tell me that doesn't make sense.
> Why on earth would you need to implement +0 for vectors?

Maybe because it makes perfect sense to treat 0 as a null vector? Or just because it comes for free (and does the right thing) if you're using numpy.array, or complex or quaternion, etc.?

> What about summing counters?

You're replying to "if you create some type that is numeric, but isn't addable to 0, you wouldn't be surprised if you couldn't sum it."

I can easily see considering a vector numeric, but a counter?

Anyway, in not sure that I agree with Alex Martelli that sum should be restricted--but if they should, I think 0+x is a much better rule than isinstance(x, Number).


More information about the Python-ideas mailing list