What is the best (idiomatic) way to check the type of a Python variable? [duplicate] What is the best (idiomatic) way to check the type of a Python variable? [duplicate] python python

What is the best (idiomatic) way to check the type of a Python variable? [duplicate]


What happens if somebody passes a unicode string to your function? Or a class derived from dict? Or a class implementing a dict-like interface? Following code covers first two cases. If you are using Python 2.6 you might want to use collections.Mapping instead of dict as per the ABC PEP.

def value_list(x):    if isinstance(x, dict):        return list(set(x.values()))    elif isinstance(x, basestring):        return [x]    else:        return None


type(dict()) says "make a new dict, and then find out what its type is". It's quicker to say just dict.But if you want to just check type, a more idiomatic way is isinstance(x, dict).

Note, that isinstance also includes subclasses (thanks Dustin):

class D(dict):    passd = D()print("type(d) is dict", type(d) is dict)  # -> Falseprint("isinstance (d, dict)", isinstance(d, dict))  # -> True


built-in types in Python have built in names:

>>> s = "hallo">>> type(s) is strTrue>>> s = {}>>> type(s) is dictTrue

btw note the is operator. However, type checking (if you want to call it that) is usually done by wrapping a type-specific test in a try-except clause, as it's not so much the type of the variable that's important, but whether you can do a certain something with it or not.