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:

  1. [Errno 13] Permission denied: ‘/root/.python-eggs’ [SOLVED]
  2. Python & Oracle [SOLVED] ImportError: libclntsh.so.11.1: wrong ELF class: ELFCLASS32
  3. Python: autocomplete names with tab key [solved]
  4. dePython, a python decompiler
  5. Utilizando ECLIPSE para programar python en entorno git

Leave a Reply

Paypal donate

Please help me keep this blog up by donating.

Por favor, ayúdame a continuar con el blog donando.