1

I'm quite sure I'm doing something foolish but can't figure out what it is.

predict  = fn_abc(data)

In[3]: predict
Out[3]: array([2])
In[4]: type(predict)
Out[4]: numpy.ndarray

Now wrapping my fn_abc with int

predict  = int(fn_abc(data))

In[6]: predict
Out[6]: 2
In[7]: type(predict)
Out[7]: int
In[8]: predict is int
Out[8]: False

What am I doing wrong?

pepe
  • 9,799
  • 25
  • 110
  • 188
  • 2
    You have misunderstood the meaning of `is`. Try http://stackoverflow.com/questions/13650293/understanding-pythons-is-operator – Alex Hall May 23 '16 at 23:16

3 Answers3

4

Use isinstance.

isinstance(predict, int)
tavo
  • 440
  • 2
  • 9
3

predict is int checks whether the integer has the same identity as the integer type object. It does not. That integer's type, however, is equal to the integer type object. Check whether the integer's type is equal to the integer type object.

>>> type(2) == int
True

You can expand this check to also handle subclasses with the built-in function isinstance():

>>> isinstance(2, int)
True
>>> isinstance(True, int)
True

The second test checks whether True is an instance of an integer. Since bool is a subclass of int, this is accurate. This is useful for user-defined classes - if you have a Person class with a Customer subclass, isinstance() will tell you that a Customer object is also a Person. However, not all Person objects are Customer objects, so it is not commutative (as shown below with bool and an integer):

>>> isinstance(2, bool)
False
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
2
type(predict) is int

predict is 2; is int checks to see whether the other item is type 'int', but 2 is not a type.

There is also an isinstance method that would be even better.

Prune
  • 76,765
  • 14
  • 60
  • 81