How to determine the variable or object type in Python?

+1 vote
39 views
asked Nov 24, 2016 by Hitesh Garg (132 points)  

I have some variables and I have to perform some operations on them based on the type of variable they are.
Is there a convenient way to check the type of variable in python?

1 Answer

+1 vote
answered Nov 24, 2016 by Rahul Singh (163 points)  
selected Nov 24, 2016 by Hitesh Garg
 
Best answer

In python there are two ways to identify the type of object -

  • Using type(obj) method - which returns the type of variable passed as an argument.

    type([]) is list #True
    type({}) is dict #True
    type('') is str #True
    type(0) is int #True
    type({}) #
    type([]) #

This of course also works for custom types:

class Test1 (object):
        pass
class Test2 (Test1):
       pass
a = Test1()
b = Test2()
type(a) is Test1  #True
type(b) is Test2  #True

Note that type() will only return the immediate type of the object, but won’t be able to tell you about type inheritance.

type(b) is Test1  #False
  • Using isinstance(obj, type) method - which returns whether the type of object is same as the type passed. This also tells you about type inheritance -

    isinstance(b, Test1) #True
    isinstance(b, Test2) #True
    isinstance(a, Test1) #True
    isinstance(a, Test2) #False
    isinstance([], list) #True
    isinstance({}, dict) #True

We generally prefer the isinstance() to ensure the type of an object because it will also accept derived types.

The second parameter of isinstance() also accepts a tuple of types, so it’s possible to check for multiple types at once. isinstance will then return true, if the object is of any of those types:

isinstance([], (tuple, list, set))  #True
Welcome to Codingeek Q&A, where you can ask questions and receive answers from other members of the community.
...