Python check instances of classes

PythonObjectInstance

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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.

Solution 3 - Python

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

Solution 4 - Python

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

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

Solution 5 - Python

I'm late. anyway think this should work.

is_class = hasattr(obj, '__name__')

Solution 6 - Python

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

Solution 7 - Python

or

import inspect
inspect.isclass(myclass)

Solution 8 - Python

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

Solution 9 - Python

Here's a dirt trick.

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

Solution 10 - Python

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

Solution 11 - Python

> 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

Solution 12 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionexbluesbreakerView Question on Stackoverflow
Solution 1 - PythonMatt AlcockView Answer on Stackoverflow
Solution 2 - PythonBerView Answer on Stackoverflow
Solution 3 - PythonRohitView Answer on Stackoverflow
Solution 4 - PythonN.C. van GilseView Answer on Stackoverflow
Solution 5 - PythonelletheeView Answer on Stackoverflow
Solution 6 - Pythonuser2682863View Answer on Stackoverflow
Solution 7 - PythonFarshid AshouriView Answer on Stackoverflow
Solution 8 - PythonNed BatchelderView Answer on Stackoverflow
Solution 9 - Pythonf.rodriguesView Answer on Stackoverflow
Solution 10 - PythonseakyView Answer on Stackoverflow
Solution 11 - PythonBion Alex HowardView Answer on Stackoverflow
Solution 12 - PythonBen HoffView Answer on Stackoverflow