What is the difference between type() and isinstance() in Python?
type(x) returns the exact class of x, so comparing with == ignores inheritance. isinstance(x, C) is True if x is an instance of C or of any subclass of C, so it is the usual choice for type checks.
Explain it simply
Suppose a college ID card says "Student". A hostel warden asks, "Is this card exactly a Student card?" That is type(). A librarian asks, "Does this person count as a student, including research scholars who are a special kind of student?" That is isinstance().
isinstance respects inheritance. Because bool is a subclass of int, True passes an int check but fails an exact type check.
Example
class Animal: pass
class Dog(Animal): pass
d = Dog()
print(type(d) == Animal) # Output: False
print(isinstance(d, Animal)) # Output: True
print(type(True) == int) # Output: False
print(isinstance(True, int)) # Output: True
print(isinstance(5, (int, float))) # Output: TrueThe last line shows that isinstance accepts a tuple of classes.
What to say in the interview
"type() gives the exact class and does not consider subclasses. isinstance() also accepts subclasses, so it works properly with inheritance and is the recommended way to check types. It also takes a tuple of types. I use type() mostly for debugging and for the rare case where an exact match is required."
Common mistakes
- Writing
type(x) == listin validation code. A subclass of list will fail it unexpectedly.