Python: how do I check the variable type? [solved]
This is a usual question in python forums. How (the hell!) do I check my variable’s type?
I am NOT a python-pro, but I have to deal with this language very often, as CDS Invenio is coded using python. Well, I was changing a function and wanted to check the type of a variable…
First of all, I thought of a quick (and really dirty) fix: I thought len(myvariablename) would return 1 if variable was not array and a higher value in other cases. But it does not behave like that. Lets see an example:
>>> myvar = "hello" >>> len(myvar) 4 >>> myvar2 = ["hello","world"] >>> len(myvar2) 2
Then I realised there is a simple (and cleaner) way of doing what I wanted:
>>> type(myvar2) <type 'list'> >>> type(myvar2) <type 'str'>
Lets imagine you want to make a conditional statement taking into account the type of a variable. Here is how you do it:
if type(myvar).__name__ == 'str': print "myvar is a string!" elif type(myvar).__name__ == 'list': print "myvar is a list!"
Hope it helps someone! If you want to learn more, check this link
Related posts: