Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python check if isinstance any type in list?

How do I pythonicly do:

var = 7.0 var_is_good = isinstance(var, classinfo1) or isinstance(var, classinfo2) or isinstance(var, classinfo3) or ... or  isinstance(var, classinfoN) 

It seems silly I can't just pass in a list of classinfo's:

var_is_good = isinstanceofany( var, [classinfo1, classinfo2, ... , classinfoN] ) 

So what is the isinstanceofany function?

like image 899
D Adams Avatar asked Oct 23 '15 20:10

D Adams


People also ask

Is instance check multiple types?

The isinstance() method can be used to check multiple types for a single object, variable, or value. Multiple types are provided as a tuple and provided as the second parameter to the isinstance() method. The syntax of checking multiple types with instance() method is like below.

How do you check if a variable is a certain type in Python?

Use the type() Function to Check Variable Type in Python To check the type of a variable, you can use the type() function, which takes the variable as an input. Inside this function, you have to pass either the variable name or the value itself. And it will return the variable data type.

How do you check if a value is in a list Python?

Check if Variable is a List with type() Now, to alter code flow programatically, based on the results of this function: a_list = [1, 2, 3, 4, 5] # Checks if the variable "a_list" is a list if type(a_list) == list: print("Variable is a list.") else: print("Variable is not a list.")


1 Answers

isinstance() takes a tuple of classes for the second argument. It'll return true if the first argument is an instance of any of the types in that sequence:

isinstance(var, (classinfo1, classinfo2, classinfo3)) 

In other words, isinstance() already offers this functionality, out of the box.

From the isinstance() documentation:

If classinfo is neither a class object nor a type object, it may be a tuple of class or type objects, or may recursively contain other such tuples (other sequence types are not accepted).

Emphasis mine; note the recursive nature; (classinfo1, (classinfo2, classinfo3)) is also a valid option.

like image 76
Martijn Pieters Avatar answered Oct 09 '22 13:10

Martijn Pieters