Article on Dispatch Decorator in Python

In Python, the @dispatch decorator enables function overloading based on argument types. This powerful feature allows you to define multiple implementations of the same function that are automatically selected at runtime based on the types of arguments passed.

Python provides two main approaches for dispatch: functools.singledispatch for single-argument dispatch and the multipledispatch library for multiple-argument dispatch.

What is Function Dispatch?

Function dispatch is a mechanism that selects the appropriate function implementation based on the types of arguments provided. Instead of writing separate function names for different types, you can use the same function name and let Python choose the correct implementation automatically.

Using functools.singledispatch

The built-in singledispatch decorator dispatches based on the type of the first argument ?

from functools import singledispatch

@singledispatch
def process_data(data):
    raise NotImplementedError("Unsupported type")

@process_data.register
def _(data: int):
    return f"Processing integer: {data * 2}"

@process_data.register
def _(data: str):
    return f"Processing string: {data.upper()}"

@process_data.register
def _(data: list):
    return f"Processing list with {len(data)} items"

# Test the function
print(process_data(42))
print(process_data("hello"))
print(process_data([1, 2, 3, 4]))
Processing integer: 84
Processing string: HELLO
Processing list with 4 items

Using multipledispatch for Multiple Arguments

For dispatching based on multiple arguments, use the multipledispatch library ?

# Note: This requires 'pip install multipledispatch'
# For demonstration, we'll show the syntax
from multipledispatch import dispatch

@dispatch(int, int)
def calculate(x, y):
    return f"Adding integers: {x + y}"

@dispatch(str, str)
def calculate(x, y):
    return f"Concatenating strings: {x + y}"

@dispatch(float, float)
def calculate(x, y):
    return f"Adding floats: {x + y:.2f}"

# Example usage (would work with multipledispatch installed)
# print(calculate(5, 10))        # Adding integers: 15
# print(calculate("Hello", "World"))  # Concatenating strings: HelloWorld
# print(calculate(3.14, 2.86))   # Adding floats: 6.00

Practical Example with Type Checking

Here's a complete example using singledispatch for handling different data formats ?

from functools import singledispatch
import json

@singledispatch
def format_output(data):
    return str(data)

@format_output.register
def _(data: dict):
    return json.dumps(data, indent=2)

@format_output.register
def _(data: list):
    return "\n".join(f"- {item}" for item in data)

@format_output.register
def _(data: int):
    return f"Number: {data:,}"

# Test with different data types
print("Dictionary:")
print(format_output({"name": "Python", "version": 3.9}))
print("\nList:")
print(format_output(["apple", "banana", "cherry"]))
print("\nInteger:")
print(format_output(1000000))
Dictionary:
{
  "name": "Python",
  "version": 3.9
}

List:
- apple
- banana
- cherry

Integer:
Number: 1,000,000

Key Benefits

Feature singledispatch multipledispatch
Built-in Yes No (requires installation)
Arguments First argument only Multiple arguments
Performance Fast Slightly slower
Use Case Simple type-based dispatch Complex multi-argument dispatch

Conclusion

Dispatch decorators provide a clean way to implement function overloading in Python. Use singledispatch for simple cases where you need to handle different types for the first argument. For more complex scenarios involving multiple arguments, consider the multipledispatch library.

Updated on: 2026-03-27T10:34:19+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements