Lin Ma Lin Ma - 1 year ago 67
Python Question

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

I tried

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

Confused why the first statement returns
and not

Answer Source

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

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

>>> type(4) is int

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

>>> isinstance(4, int)

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download