10

I want to check if an object is an instance of any class in a list/group of Classes, but I can't find if there is even a pythonic way of doing so without doing

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

I mean, comparing class by class.

It would be more likely to use some function similar to isinstance that would receive n number of Classes to compare against if that even exists.

Thanks in advance for your help!! :)

Scott C Wilson
  • 19,102
  • 10
  • 61
  • 83
Gerard
  • 9,088
  • 8
  • 37
  • 52
  • 4
    How can it be that `help(isinstance)` is harder than taking the time to post to SO? o_0 – rantanplan May 05 '12 at 01:55
  • It is worth noting that checking type/class is [generally discouraged](http://stackoverflow.com/questions/1549801/differences-between-isinstance-and-type-in-python). Duck-typing and `try`/`except` is considered a better practice. – yentsun May 05 '12 at 02:56

3 Answers3

31

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

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

Looking up the docstring would have also told you 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's type.
    The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
    isinstance(x, A) or isinstance(x, B) or ... (etc.).
Glider
  • 1,568
  • 12
  • 13
2

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

That said, you should think twice before using this. Explicit type checking like this can hurt genericity of the code, so you'd better have a reason for throwing duck typing away.

Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
-1

Another way to do it, though without subclass check:

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

Note. Probably this is just for taking into consideration, not for practical use.

yentsun
  • 2,488
  • 27
  • 36