object – Python check instances of classes

object – Python check instances of classes

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.

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.

object – Python check instances of classes

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

Leave a Reply

Your email address will not be published.