The isinstance() function in Python is used to check if an object is an instance of a specified type or class. When checking for multiple types, we can optimize our code by using a tuple of types instead of multiple isinstance() calls or conditions.
Let’s break it down:
- Traditional approach (less efficient):
def is_number(num):
return isinstance(num, int) or isinstance(num, float)
print(is_number(2)) # True
print(is_number(1.5)) # True
print(is_number("2")) # False- Optimized approach using a tuple:
def is_number(num):
return isinstance(num, (int, float))
print(is_number(2)) # True
print(is_number(1.5)) # True
print(is_number("2")) # FalseBenefits of using a tuple:
- Conciseness: The code is more readable and compact.
- Performance: It’s slightly more efficient, especially when checking against many types.
- Maintainability: Easier to add or remove types to check against.
You can extend this concept to check for more types:
def is_sequence(obj):
return isinstance(obj, (list, tuple, str))
print(is_sequence([1, 2, 3])) # True
print(is_sequence((1, 2, 3))) # True
print(is_sequence("123")) # True
print(is_sequence(123)) # FalseFor broader type checking, use Python’s abstract base classes:
from collections.abc import Sequence
def is_sequence(obj):
return isinstance(obj, Sequence)
print(is_sequence([1, 2, 3])) # True
print(is_sequence((1, 2, 3))) # True
print(is_sequence("123")) # True
print(is_sequence(123)) # FalseIn this case, we’re checking if an object is a Sequence (like lists, tuples, or strings).
Conclusion
Using tuples and abstract base classes with isinstance() makes your type checks cleaner, more maintainable, and easier to extend. These patterns help you write defensive code that catches type issues early without cluttering your logic with repetitive checks.
Read Deeper
Want cleaner, safer Python patterns? Read our deep dive: The Hidden Cost of Python Dictionaries (And 3 Safer Alternatives). Practical patterns for more robust Python code.




