3

I'm having an issue with isinstance().

I'm using Python 2.7.8, and running scripts from the shell.

The array element I'm testing for contains a number, but this function returns false; using number.Numbers:

import numbers
...
print array[x][i] 
>> 1
...
print isinstance(array[x][i], numbers.Number)
>>> False

Also tried this, from this post

import types
...
print isinstance(array[x][i], (types.IntType, types.LongType, types.FloatType, types.ComplexType))
>>> False

From the same post, I tried

isinstance(array[x][i], (int, float, long, complex))

I also tried this solution did not work.

All return false.

Community
  • 1
  • 1
JasTonAChair
  • 1,948
  • 1
  • 19
  • 31

1 Answers1

8

You don't have a number; you most probably have a string instead, containing the digit '1':

>>> value = '1'
>>> print value
1
>>> print 1
1

This is not a number; it is a string instead. Note that printing that string is indistinguishable from printing an integer.

Use repr() to print out Python representations instead, and / or use the type() function to produce the type object for a given value:

>>> print repr(value)
'1'
>>> print type(value)
<type 'str'>

Now it is clear that the value is a string, not an integer, even though it looks the same when printed.

For actual numeric values, isinstance() together with numbers.Number works as expected:

>>> from numbers import Number
>>> isinstance(value, Number)
False
>>> isinstance(1, Number)
True
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343