Search code examples
pythoninstancedynamic-typing

Python type comparision


Ok, so I have a list of tuples containing a three values (code, value, unit)

when I'm to use this I need to check if a value is an str, a list or a matrix. (or check if list and then check if list again)

My question is simply should I do like this, or is there some better way?

for code, value, unit in tuples:
    if isinstance(value, str): 
        # Do for this item
    elif isinstance(value, collections.Iterable):
        # Do for each item
        for x in value:
             if isinstance(x, str):
                  # Do for this item
             elif isinstance(x, collections.Iterable):
                  # Do for each item
                  for x in value:
                      # ...
             else:
                  raise Exception
    else:
        raise Exception

Solution

  • The best solution is to avoid mixing types like this, but if you're stuck with it then what you've written is fine except I'd only check for the str instance. If it isn't a string or an iterable then you'll get a more appropriate exception anyway so no need to do it yourself.

    for (code,value,unit) in tuples:
        if isinstance(value,str): 
            #Do for this item
        else:
            #Do for each item
            for x in value:
                 if isinstance(value,str):
                      #Do for this item
                 else:
                      #Do for each item
                      for x in value: