How to compare inheritance with multiple classes?

I want to check if an object is an instance of any class in the list / group of classes, but I can not find if there is even a pythonic way to do this without doing

if isinstance(obj, Class1) or isinstance(obj, Class2) ... or isinstance(obj, ClassN): # proceed with some logic 

I mean, comparing a class by class.

It would be more likely to use some function similar to isinstance , which would get n number of classes to compare, if that even exists.

Thank you in advance for your help! :)

+8
python
source share
3 answers

You can pass a tuple of classes as the 2nd argument to isinstance.

 >>> isinstance(u'hello', (basestring, str, unicode)) True 

Raising the doctrine, you would also say that though;)

 >>> help(isinstance) Help on built-in function isinstance in module __builtin__: isinstance(...) isinstance(object, class-or-type-or-tuple) -> bool Return whether an object is an instance of a class or of a subclass thereof. With a type as second argument, return whether that is the object type. The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for isinstance(x, A) or isinstance(x, B) or ... (etc.). 
+25
source share

isinstance(obj, (Class1, Class2, ..., ClassN)) or isinstance(obj, BaseClass) if they have a common ancestor.

However, you should think twice before using this. Explicit type checking like this can damage the generality of the code, so you will have more reasons to drop the duck print.

+2
source share

Another way to do this, although without checking the subclass:

 >>> obj = Class2() >>> type(obj) in (Class1, Class2, Class3) True 

Note. This is probably just for consideration, and not for practical use.

-one
source share

All Articles