Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Filter by Categories
About Article
Analyze Data
Archive
Best Practices
Better Outputs
Blog
Code Optimization
Code Quality
Command Line
Daily tips
Dashboard
Data Analysis & Manipulation
Data Engineer
Data Visualization
DataFrame
Delta Lake
DevOps
DuckDB
Environment Management
Feature Engineer
Git
Jupyter Notebook
LLM
LLM
Machine Learning
Machine Learning
Machine Learning & AI
Manage Data
MLOps
Natural Language Processing
NumPy
Pandas
Polars
PySpark
Python Tips
Python Utilities
Python Utilities
Scrape Data
SQL
Testing
Time Series
Tools
Visualization
Visualization & Reporting
Workflow & Automation
Workflow Automation

Simplify Multiple Type Checks in Python: Tuples and Abstract Base Classes

Table of Contents

Simplify Multiple Type Checks in Python: Tuples and Abstract Base Classes

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:

  1. 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
  1. 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:

  1. Conciseness: The code is more readable and compact.
  2. Performance: It’s slightly more efficient, especially when checking against many types.
  3. 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).

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran