How to determine the variable or object type in Python?

+1 vote
209 views
asked Nov 24, 2016 by Hitesh Garg (352 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 (543 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

124 questions

41 answers

3 comments

926 users

Most popular tags

java python python3 oracle database java-8 sql-server python2 oracle11g git oracle-12g command-line maven sql-server-2012 sql input array list fenitoina dilantin java的 angular javascripts git-branch intellij-idea hashmap collection file-io io temovate clobetasol ampicillin principen daclatasvir daklinza vasotec enalapril nexium esomeprazole tadalafil tadlis sildenafil citrate pefomax xeloda capecitabina clobetasol temovate stemetil prochlorperazine methotrexate methotrexate sildenafilo y dapoxetina super kamagra norvasc amlodipine citalopram celexa amitriptylin saroten vitamin b12 methylcobalamin valaciclovir valtrex zudena udenafil sildenafil citrate vigour depakote divalproex retin-a tretinoine sildenafil citrate ip-max nizoral ketoconazol ciaton tadalafil norethisteronacetat aygestin indomethacin indocin tiova tiotropium bromid finasterida proscar lithium carbonate eskalith finasterida propecia levitra vardenafil vantin cefpodoxima loxitane loxapine rulide roxithromycine avodart dutasterid tecnomax sildenafil citrate methylcobalamin vitamin b12 permethrin acticin etinilestradiol norgestrel ovral pk-merz amantadin cycrin medroxyprogesterone serophene clomiphene spironolactone aldactone mesalazin pentasa zebeta bisoprolol cytodrox hydroxyurea ampicillin ampicillin pletal cilostazol paracetamol panadol pepcid famotidina meclizine hydrochloride antivert donaton tadalafil sdf dsfs sdgfgsdg mac null-pointer-exception constructor oracle-12c terminal hibernate-5 hibernate git-merge es6 programming git-amend git-commit java-stream git-remote multithreading access-modifiers nested-classes
Welcome to Codingeek Q&A, where you can ask questions and receive answers from other members of the community.
...