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")) # False
Benefits 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)) # False
For 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)) # False
In this case, we’re checking if an object is a Sequence (like lists, tuples, or strings).