Last modified: Apr 09, 2025 By Alexander Williams
Fix TypeError: isinstance() arg 2 Must Be Type
Python's isinstance()
function checks if an object is an instance of a class. This error occurs when the second argument is not a valid type.
Table Of Contents
What Causes This Error?
The error happens when you pass an invalid second argument to isinstance()
. The second argument must be a type or a tuple of types.
Common causes include passing a string, an instance, or an incorrect value as the second argument.
Understanding isinstance()
The isinstance()
function takes two arguments: an object and a type (or tuple of types). It returns True
if the object is an instance of the specified type.
# Correct usage
num = 10
print(isinstance(num, int)) # True
True
Common Error Examples
Here are examples that trigger the error and how to fix them:
1. Passing a String Instead of Type
# Wrong way (causes error)
value = "hello"
print(isinstance(value, "str")) # TypeError
The fix is to pass the type itself, not its name as a string:
# Correct way
value = "hello"
print(isinstance(value, str)) # True
2. Passing an Instance Instead of Type
# Wrong way (causes error)
num = 10
other_num = 20
print(isinstance(num, other_num)) # TypeError
Pass the type (int
), not an instance of the type:
# Correct way
num = 10
print(isinstance(num, int)) # True
3. Using Tuple of Types Correctly
You can check against multiple types using a tuple:
# Correct usage with tuple
value = 3.14
print(isinstance(value, (int, float))) # True
Important: The tuple must contain only types, not other values.
Advanced Usage
You can use isinstance()
with custom classes and modules. For module checks, ensure the module is imported correctly to avoid ModuleNotFoundError.
# Custom class example
class MyClass:
pass
obj = MyClass()
print(isinstance(obj, MyClass)) # True
Debugging Tips
1. Verify the second argument is a type object
2. Check for typos in type names
3. For custom types, ensure the class is defined
4. When using tuples, ensure all elements are types
Conclusion
The isinstance()
error occurs when the second argument isn't a valid type. Always pass a type object or tuple of types. This is different from checking module imports where you might encounter a ModuleNotFoundError.
Remember: the second argument must be a type, not an instance, string, or other value. With proper usage, isinstance()
is powerful for type checking in Python.