Python isinstance() Function
The isinstance() function in Python checks whether a variable is an instance of a specific class or a tuple of classes. It's a safe and recommended way to validate data types.
Syntax
isinstance(object, classinfo)
Parameters:
object– The value or variable to test.classinfo– A class, type, or a tuple of classes and types.
Returns:
Trueifobjectis an instance (or subclass instance) ofclassinfo.Falseotherwise.
Example 1: Check if a variable is an integer
x = 5
print(isinstance(x, int))
True
Example 2: Check if a string is a list (it isn’t)
name = "Alice"
print(isinstance(name, list))
False
Example 3: Check against multiple types
value = 3.14
print(isinstance(value, (int, float)))
True
Here, value is checked against both int and float. The function returns True if it matches any one.
Use Case: Why Use isinstance()?
- To validate function arguments
- To avoid type errors in logic
- To write type-safe code, especially in large projects
- To apply different logic based on variable type (e.g., float vs int)
Example 4: Type checking in a function
def square(x):
if isinstance(x, (int, float)):
return x * x
else:
return "Invalid input"
print(square(4)) # 16
print(square("four")) # Invalid input
16
Invalid input
Common Mistakes
- Passing a string for
classinfolike"int"(should beintwithout quotes) - Confusing
type()withisinstance():isinstance()supports inheritance,type()does not
Interview Tip
isinstance() is often used in questions involving type safety or when a function needs to behave differently based on data types. It’s also commonly used in object-oriented questions.
Summary
isinstance(obj, type)returnsTrueifobjis of the given type or its subclass.- Use a tuple to check against multiple types.
- Safer than using
type()when inheritance is involved.
Practice Problem
Write a function that accepts a value and returns:
"Integer"if it’s an integer"Float"if it’s a float"Other"otherwise
def identify_type(x):
if isinstance(x, int):
return "Integer"
elif isinstance(x, float):
return "Float"
else:
return "Other"
print(identify_type(42))
print(identify_type(3.14))
print(identify_type("hello"))
Integer
Float
Other
Comments
Loading comments...