check if object is number
Steven Bethard
steven.bethard at gmail.com
Fri Feb 11 18:07:48 EST 2005
John Lenton wrote:
> On Fri, Feb 11, 2005 at 01:17:55PM -0700, Steven Bethard wrote:
>
>>George Sakkis wrote:
>>
>>>"Steven Bethard" <steven.bethard at gmail.com> wrote in message
>>>news:gcidnb9g_ojxnpDfRVn-tA at comcast.com...
>>>
>>>
>>>>Is there a good way to determine if an object is a numeric type?
>>>
>>>In your example, what does your application consider to be numeric?
>>
>>Well, here's the basic code:
>>
>>def f(max=None):
>> ...
>> while max is None or n <= max:
>> ...
>> # complicated incrementing of n
>>
>>So for 'max', technically all I need is <= support. However, the code
>>also depends on the fact that after incrementing 'n' enough, it will
>>eventually exceed 'max'. Currently, ints, longs, floats, and Decimals
>>will all meet this behavior. But I'd rather not specify only those 4
>>(e.g. with a typecheck), since someone could relatively easily create
>>their own new numeric type with the same behavior. Do you know a better
>>way to test for this kind of behavior?
>
>
> Why don't you express just this need as an assertion?
>
> assert 0 <= max <= max + 1, 'Argument must not be zany'
Well a TypeError might be raised in executing the expression:
py> max = complex(0, 1)
py> assert 0 <= max <= max + 1, 'Argument must not be zany'
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: cannot compare complex numbers using <, <=, >, >=
but I do like the max <= max + 1 idea. Maybe I should do something like:
py> def assertnumber(x):
... try:
... 1 < x
... except TypeError:
... raise TypeError('%s is not comparable to int' %
... type(x).__name__)
... try:
... if not x <= x + 1:
... raise TypeError
... except TypeError:
... raise TypeError('%s is not monotonic' %
... type(x).__name__)
...
py> assertnumber(1)
py> assertnumber(1.0)
py> assertnumber(complex(0, 1))
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "<interactive input>", line 5, in assertnumber
TypeError: complex is not comparable to int
py> assertnumber('a')
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "<interactive input>", line 11, in assertnumber
TypeError: str is not monotonic
py> class C(object):
... def __add__(self, other):
... return 0
... def __lt__(self, other):
... return True
...
py> assertnumber(C())
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "<interactive input>", line 11, in assertnumber
TypeError: C is not monotonic
Steve
More information about the Python-list
mailing list