[Python-ideas] `numbers.Natural`

Andrew Barnert abarnert at yahoo.com
Fri Sep 26 23:00:12 CEST 2014


On Sep 26, 2014, at 13:33, Ethan Furman <ethan at stoneleaf.us> wrote:

> On 09/26/2014 01:27 PM, Ian Cordasco wrote:
>> 
>> The only motivations I can think of for making this a type (not that
>> they're good ones) is you could do something like:
>> 
>> if isinstance(x, (Natural, Complex, Real)):
>>    #
>> elif isinstance(x, Rational):
>>    #
>> else:
>>    raise ValueError
>> 
>> Which is naturally (no pun intended) slightly nicer than
>> 
>> if isinstance(x, (Complex, Real)) or isNatural(x):
>>     #
> 
> The Good Reason for having a Natural type would be not having to always check for illegal values -- if one is (attempted to be) created, an exception is raised on the spot.
> 
> n5 = Natural(5)
> n7 = Natural(7)
> n5 - n7
> Traceback...

Except that 2/3 is a float, and (-1)**.5 is a complex, so it might be perfectly reasonable to expect n5-n7 to be an int. Or maybe Natural(0) or Natural('nan') even, on analogy with 2//3 and whatever float operations return NaN values.

As I said in my first message, which one makes more sense probably depends on your application, which is part of why this doesn't belong in the stdlib in the first place... But if it did belong, I'd expect it to act like int and float and underflow to an int. (In which case a type check for Natural might be sensible, but would not often be useful--just like a type check on the result of a/b for integers is sensible but not often useful.)


More information about the Python-ideas mailing list