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

Joshua Landau joshua.landau.ws at gmail.com
Sun Jul 7 03:08:15 CEST 2013


On 7 July 2013 01:30, Andrew Barnert <abarnert at yahoo.com> wrote:
> 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:
>>>>
>>>> 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.?

I said why would you *need* to, not why would you. You can if you want.

>> 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."

Well, also to:
> But I think [being addable to 0] is actually a good rule for "is summable"

> 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).

Fair 'nuff. That wasn't clear from what you said, though.


More information about the Python-ideas mailing list