88
votes

Is there any way to check if object is an instance of a class? Not an instance of a concrete class, but an instance of any class.

I can check that an object is not a class, not a module, not a traceback etc., but I am interested in a simple solution.

12
Every python object is an instance of some class (built-in or otherwise). - StoryTeller - Unslander Monica
So the solution is the function def isobject(x): return True - Emanuele Paolini
If i write from my_module import MyClass will be class object, not instance of class, similiarly for traceback, function, module. inspect module contains special checking functions for this type of objects, but no function for instances of classes. Roughly, i want to detect all objects, for which print obj will print <instance of ...> (if no special printing defined for class) - exbluesbreaker
A class is just an instance of another class (called metaclass when the distinction matters; commonly type but anyone can define a metaclass, IIRC even without inheriting from type). A traceback is just an instance of traceback. A function is just an instance of function. A method is just an instance of a class too (which depends on what exactly you mean by method). You'll have to be more specific -- or even better, just tell us your actual problem. - user395760

12 Answers

108
votes

isinstance() is your friend here. It returns a boolean and can be used in the following ways to check types.

if isinstance(obj, (int, long, float, complex)):
    print obj, "is a built-in number type"

if isinstance(obj, MyClass):
    print obj, "is of type MyClass"

Hope this helps.

26
votes

Have you tried isinstance() built in function?

You could also look at hasattr(obj, '__class__') to see if the object was instantiated from some class type.

9
votes

If you want to check that an object of user defined class and not instance of concrete built-in types you can check if it has __dict__ attribute.

>>> class A:
...     pass
... 
>>> obj = A()
>>> hasattr(obj, '__dict__')
True
>>> hasattr((1,2), '__dict__')
False
>>> hasattr(['a', 'b', 1], '__dict__')
False
>>> hasattr({'a':1, 'b':2}, '__dict__')
False
>>> hasattr({'a', 'b'}, '__dict__')
False
>>> hasattr(2, '__dict__')
False
>>> hasattr('hello', '__dict__')
False
>>> hasattr(2.5, '__dict__')
False
>>> 

If you are interested in checking if an instance is an object of any class whether user defined or concrete you can simply check if it is an instance of object which is ultimate base class in python.

class A:
    pass
a = A()
isinstance(a, object)
True
isinstance(4, object)
True
isinstance("hello", object)
True
isinstance((1,), object)
True
8
votes

I had a similar problem at this turned out to work for me:

def isclass(obj):
    return isinstance(obj, type)
6
votes

I'm late. anyway think this should work.

is_class = hasattr(obj, '__name__')
5
votes
class test(object): pass
type(test)

returns

<type 'type'>

instance = test()
type(instance)

returns

<class '__main__.test'>

So that's one way to tell them apart.

def is_instance(obj):
    import inspect, types
    if not hasattr(obj, '__dict__'):
        return False
    if inspect.isroutine(obj): 
        return False
    if type(obj) == types.TypeType: # alternatively inspect.isclass(obj)
        # class type
        return False
    else:
        return True
2
votes

It's a bit hard to tell what you want, but perhaps inspect.isclass(val) is what you are looking for?

2
votes

or

import inspect
inspect.isclass(myclass)
2
votes

Here's a dirt trick.

if str(type(this_object)) == "<type 'instance'>":
    print "yes it is"
else:
    print "no it isn't"
2
votes

Yes. Accordingly, you can use hasattr(obj, '__dict__') or obj is not callable(obj).

1
votes

Is there any way to check if object is an instance of a class? Not an instance of a concrete class, but an instance of any class.

I can check that an object is not a class, not a module, not a traceback etc., but I am interested in a simple solution.

One approach, like you describe in your question, is a process of exclusion, check if it isn't what you want. We check if it's a class, a module, a traceback, an exception, or a function. If it is, then it's not a class instance. Otherwise, we return True, and that's potentially useful in some cases, plus we build up a library of little helpers along the way.

Here is some code which defines a set of type checkers and then combines them all to exclude various things we don't care about for this problem.

from types import (
    BuiltinFunctionType,
    BuiltinMethodType,
    FunctionType,
    MethodType,
    LambdaType,
    ModuleType,
    TracebackType,
)
from functools import partial
from toolz import curry
import inspect
    
def isfunction(variable: any) -> bool:
    return isinstance(
        variable,
        (
            BuiltinFunctionType,
            BuiltinMethodType,
            FunctionType,
            MethodType,
            LambdaType,
            partial,
            curry
        ),
    )
    
isclass = inspect.isclass
    
def ismodule(variable: any) -> bool:
   return isinstance(variable, ModuleType)
    
    
def isexception(variable: any) -> bool:
    return isinstance(variable, Exception)
    
    
def istraceback(variable: any) -> bool:
    return isinstance(variable, TracebackType)
    
    
def isclassinstance(x: any) -> bool:
    if isfunction(x) or isclass(x) or ismodule(x) or istraceback(x) or isexception(x):
        return False
    return True

keep in mind, from a hella abstract perspective, everything is a thing, even categories of things or functions ... but from a practical perspective, this could help avoid mistaking MyClass for my_class_instance (the python community also does this informally with PascalCase vs snake_case)

we could improve this

0
votes

Had to deal with something similar recently.

import inspect

class A:
    pass

def func():
    pass

instance_a = A()

def is_object(obj):
     return inspect.isclass(type(obj)) and not type(obj) == type

is_object(A)          # False
is_object(func)       # False
is_object(instance_a) # True