Difference Between type()
and isinstance()
in Python
Both type()
and isinstance()
are used to check the type of an object in Python, but they behave differently.
1. type()
- Returns the exact type of an object.
- Does not consider inheritance.
Syntax
type(object)
Example
print(type(10)) # Output: <class 'int'>
print(type("Hello")) # Output: <class 'str'>
print(type(3.14)) # Output: <class 'float'>
Limitation: Ignores Inheritance
class Animal: pass
class Dog(Animal): pass
d = Dog()
print(type(d) == Dog) # ✅ True
print(type(d) == Animal) # ❌ False (even though Dog is a subclass of Animal)
type(d)
is onlyDog
, it does not recognizeAnimal
.
2. isinstance()
- Checks if an object belongs to a specific class or its subclass.
- Supports inheritance.
Syntax
isinstance(object, class_or_tuple)
print(isinstance(10, int)) # ✅ True
print(isinstance("Hello", str)) # ✅ True
print(isinstance(3.14, (int, float))) # ✅ True (checks multiple types)
Supports Inheritance
class Animal: pass
class Dog(Animal): pass
d = Dog()
print(isinstance(d, Dog)) # ✅ True
print(isinstance(d, Animal)) # ✅ True (inherits from Animal)
isinstance(d, Animal)
recognizes thatDog
is a subclass ofAnimal
.
Key Differences
Feature | type() |
isinstance() |
---|---|---|
Checks exact type? | ✅ Yes | ❌ No (considers inheritance) |
Checks parent class? | ❌ No | ✅ Yes |
Supports multiple types? | ❌ No | ✅ Yes (isinstance(obj, (int, float)) ) |
Used for strict type checking? | ✅ Yes | ❌ No |
When to Use Which?
✔ Use type()
when you need an exact match and don’t care about inheritance.
✔ Use isinstance()
when you want to check if an object belongs to a class or subclass.
Leave a comment