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

Andrew Barnert abarnert at yahoo.com
Sat Jul 6 09:07:11 CEST 2013


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.



More information about the Python-ideas mailing list