What is isinstance()
in Python?
isinstance()
is a built-in Python function used to check if a variable is of a specific type or class. It's often used for data validation, type checking, and writing safer, more readable code.
Syntax
isinstance(object, classinfo)
-
object
: the variable you want to check -
classinfo
: a type or a tuple of types (e.g.,int
,str
,(int, float)
)
-
True
if the object matches the type(s) -
False
otherwise
Example 1: Check for Integer
x = 10
if isinstance(x, int):
print("x is an integer")
Output:
x is an integer
Example 2: Multiple Types
x = 3.14
if isinstance(x, (int, float)):
print("x is a number")
Output:
x is a number
Example 3: Validate User Input
user_input = "123"
if isinstance(user_input, str):
try:
num = int(user_input)
print("Converted to integer:", num)
except ValueError:
print("Not a valid number string")
Use Case Examples
Use Case | Code Example |
---|---|
Check if a value is a list | isinstance(data, list) |
Check if value is a number | isinstance(x, (int, float)) |
Avoid AttributeError on wrong type | Use isinstance(obj, str) before .upper() |
Validate function arguments | Combine with raise TypeError(...) if invalid |
Common Mistakes
Using type()
for validation in the wrong way:
type(5) == int # Works, but less flexible
Better:
isinstance(5, int)
isinstance()
supports inheritance, while type()
does not.
Advanced Tip: Custom Classes
class Animal:
pass
class Dog(Animal):
pass
d = Dog()
print(isinstance(d, Animal)) # True, because Dog is a subclass of Animal
Summary
Task | Recommended Code |
---|---|
Check for a specific type | isinstance(x, int) |
Check for multiple types | isinstance(x, (int, float)) |
Check before method call | if isinstance(s, str): s.upper() |
Works with inheritance | Yes |
0 Comments:
Post a Comment