Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to know if a variable in Python is a string or a dict. Is there anything wrong with the following code?

if type(x) == type(str()):     do_something_with_a_string(x) elif type(x) == type(dict()):     do_somethting_with_a_dict(x) else:     raise ValueError 

Update: I accepted avisser's answer (though I will change my mind if someone explains why isinstance is preferred over type(x) is).

But thanks to nakedfanatic for reminding me that it's often cleaner to use a dict (as a case statement) than an if/elif/else series.

Let me elaborate on my use case. If a variable is a string, I need to put it in a list. If it's a dict, I need a list of the unique values. Here's what I came up with:

def value_list(x):     cases = {str: lambda t: [t],              dict: lambda t: list(set(t.values()))}     try:         return cases[type(x)](x)     except KeyError:         return None 

If isinstance is preferred, how would you write this value_list() function?

like image 953
Daryl Spitzer Avatar asked Dec 18 '08 19:12

Daryl Spitzer


People also ask

How do you check the type of a variable in Python?

To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.

How do you check if the same type in Python?

Python has a built-in function called instance() that compares the value with the type given. It the value and type given matches it will return true otherwise false. Using isinstance(), you can test for string, float, int, list, tuple, dict, set, class, etc.


1 Answers

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 
like image 177
Suraj Avatar answered Oct 02 '22 16:10

Suraj