Search code examples
pythontypesdetection

How do I tell what type of data is inside python variable?


I have a list of variables.. inside the list are strings, numbers, and class objects. I need to perform logic based on each different type of data. I am having trouble detecting class objects and branching my logic at that point.

if(type(lists[listname][0]).__name__ == 'str'): # <--- this works for strings
elif(type(lists[listname][0]).__name__ == 'object'): <--- this does not work for classes

in the second line of code above, the name variable contains "Address" as the class name. I was hoping it would contain "class" or "object" so I could branch my program. I will have many different types of objects in the future, so it's a bit impractical to perform logic on every different class name, "Address" "Person" etc

please let me know if my question needs clarification.

thanks!!


Solution

  • I think you want the isinstance function.

    if isinstance(o, ClassName):
    

    However, you'll need to first verify that o is an object, you can use type for that.