isinstance(type, object) = True, why?

1.1k Views Asked by At

I have an understanding that object is an instance of type and type inherits from object. So the following relationships makes sense:

isinstance(object, type)            # returns True, ok
issubclass(type, object)            # returns True, ok

I also know that isinstance(a,b) checks whether a is an instance of either b or its bases. So, the following makes sense too:

isinstance(type, type)              # returns True because it is translated to ....
isinstance(type, object)            # which is True

What I cannot follow is why do the following statements return True.

isinstance(type, object)            # returns True, but why?
isinstance(object, object)          # returns True, but why?

Let me know if you know. Thanks.

2

There are 2 best solutions below

3
chepner On

object is the root of the class hierarchy, so it is the ultimate parent class of every type, including type and object. That makes object its own parent class, which is one reason why you could not define object in Python alone; it has to be dragged kicking and screaming out of thin air by the Python implementation.

type is a class, and all (built-in) classes are instances of the meta class type. (Yes, type is its own metaclass.) And since object is the base class of type, therefore type is an instance of object.

0
hygull On

Everything in Python is an object. By default all the objects are instance of object superclass so instance(type, object returns True

object class is in the top of objects hierarchy. Even if A is direct child of B (in below example) and both are indirect children of object.

isinstance() method is coded in such a way that it returns True if both the parameters are object. In other cases it checks whether first parameter is instance of second parameter or not.

Please have a look at the below code example.

class A:
       pass

class B(A):
        pass

a = A()
b = B()

print(isinstance (a, A)) # True
print(isinstance (b, B)) # True
print(isinstance (b, A)) # True
print(isinstance (a, B)) # False

print(isinstance (a, object)) # True
print(isinstance (b, object)) # True
print(isinstance (A, object) ) # True
print(isinstance (B, object)) # True

object is an instance of object.

print(isinstance (object, object)) # True

A is not an instance of A, same is for B.

print(isinstance (B, B)) # False
print(isinstance (A, A)) # False

The following code throws error as the second parameter should be a name of class.

print(isinstance (a, a)) 
"""
print(isinstance (a, a)) 
TypeError: isinstance() arg 2 must be a type or tuple of 
types
"""

print(isinstance (b, b)) 
"""
print(isinstance (b, b)) 
TypeError: isinstance() arg 2 must be a type or tuple of  
types
"""

So it is all about the code logic or implementation of isinstance() method that it returns True if both the pararamers are object.