Fix Python – Python check if variable isinstance of any type in list

Question

Asked By – D Adams

How do I compactly perform the following:

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

Now we will see solution for issue: Python check if variable isinstance of any type in list


Answer

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.

This question is answered By – Martijn Pieters

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0