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.

3
  • 2
    What does print repr(array[x][i]), type(array[x][i]) produce? Commented Apr 12, 2015 at 1:53
  • what is the output of type(array[x][i]) ? Commented Apr 12, 2015 at 1:54
  • You could have a string for example; if array[x][i] stores '1', then print will produce that exact same output. Commented Apr 12, 2015 at 1:54

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for putting that in context. It only looked like an integer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.