Skip to content

Archive

Single Dispatch

1 articles
Python 03 Sep 2026 10 min read

Use Single Dispatch for Type-Based Behavior in Python

A function sometimes needs to perform the same conceptual operation for several unrelated Python types. The straightforward solution is usually an if chain: def format_value(value): if isinstance(value, str): return value if isinstance(value, int): return str(value) if isinstance(value, dict): return ", ".join(f"{key}={item}" for key, item in value.items()) raise TypeError(f"unsupported type: {type(value).__name__}") This is perfectly reasonable when the set of supported types is small and unlikely to grow.