[SciPy-User] Integer dtype comparisons

Travis Oliphant oliphant@enthought....
Wed Sep 29 13:59:59 CDT 2010



On Sep 22, 2010, at 7:04 AM, Michael Pimmer wrote:

> Hello,
> 
> is there a nice way to check whether an object is an Integer? Including 
> all python and numpy Integers?

All numpy integers inherit from a base-class numpy.integer. 

Thus,  isinstance(obj, (numpy.integer, int, long))  should work. 

But, you might want to think about "duck-typing" (i.e why do you need to do this check) and use a try, except approach with the __index__() method of the object instead. 

The __index__() object returns a real Python int from any object that supports it.  

Example
======= 

try:
	obj_as_integer =	obj.__index__()
        # code to use obj_as_integer
except (TypeError, AttributeError):
	# some other code....




-Travis



> 
> I tried out subclass, but uint is not a subclass of Int:
> 
>>>> a = numpy.zeros(1,numpy.uint32)
>>>> aType = type(a[0])
>>>> issubclass(aType,types.IntType)
> False
> 
> 
> I tried out enumerating, but numpy seems to slightly change datatypes 
> during some calculations, which complicates comparisons:
> 
>>>> a = numpy.zeros(1,numpy.uint8)
>>>> aValue = a[0]
>>>> b = numpy.zeros(1,numpy.int32)
>>>> bValue = b[0]
>>>> result = aValue + bValue
>>>> type(result)
> <type 'numpy.int32'>
>>>> numpy.int32
> <type 'numpy.int32'>
>>>> type(result) == numpy.int32
> False
> 
> 
> thanks,
> Michael
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user

---
Travis Oliphant
Enthought, Inc.
oliphant@enthought.com
1-512-536-1057
http://www.enthought.com





More information about the SciPy-User mailing list