Type-Safe Checks with Python's isinstance()
Type-Safe Checks with Python's isinstance() ๐ง
The isinstance() function in Python is a powerful way to verify the type of an object.
Unlike type(), it also considers inheritance, making it a safer choice in many cases.
✅ Basic Usage
Returns True or False depending on whether the object is of the specified type.
# Basic usage
x = 10
print(isinstance(x, int)) # True
print(isinstance(x, str)) # False
✅ Validating Common Types
Use it to check if data is a list, dictionary, or any other structure.
# Checking lists and dictionaries
data = [1, 2, 3]
config = {"debug": True}
print(isinstance(data, list)) # True
print(isinstance(config, dict)) # True
✅ Checking Against Multiple Types
Use a tuple to check if a value matches any of several possible types.
# Checking multiple types
value = "hello"
print(isinstance(value, (int, float, str))) # True
✅ Inheritance-Aware Type Checking
isinstance() returns True even for inherited types, unlike type().
# Checking custom class and inheritance
class Animal:
pass
class Dog(Animal):
pass
a = Animal()
b = Dog()
print(isinstance(b, Animal)) # True (inherited)
Using isinstance() is essential for robust input validation, class-based logic, and writing defensive code.
It’s one of the simplest ways to make your Python applications safer and smarter.
Robust code starts with precise type checks. Know your data, trust your structure — and keep building with confidence. ๐
Icons by Flaticon
Comments
Post a Comment