Lin Ma Lin Ma - 5 months ago 9
Python Question

type(4) == type(int) is False in Python?

I tried

type(4) == type(int)
, which returns
False
, but
print type(4)
returns
<type 'int'>
, so 4 is obviously
int
.

Confused why the first statement returns
False
and not
True
?

Answer

The type of int is type itself:

>>> type(int)
<type 'type'>

You'd compare with int directly; int is, after all, a type, as we established above:

>>> type(4) == int
True

or even, since int is a singleton, like all types should be:

>>> type(4) is int
True

However, the proper way to test for types is to use the isinstance() function:

>>> isinstance(4, int)
True

isinstance() also allows for any subclasses of int to pass this test; a subcclass is always considered to be at least an int. That includes any custom subclasses you could build yourself, and still have it work as an int everywhere else in your code.