How to Use singledispatch for Type-Based Overloading in Python
This code demonstrates Python's functools.singledispatch decorator to create functions that behave differently based on the type of their first argument.
Python code
28 linesfrom functools import singledispatch
@singledispatch
def process(value):
return f"Unknown type: {type(value).__name__}"
@process.register(int)
def _(value):
return f"Integer: {value * 2}"
@process.register(str)
def _(value):
return f"String: {value.upper()}"
@process.register(list)
def _(value):
return f"List: {len(value)} items"
@process.register(dict)
def _(value):
return f"Dict: {len(value)} keys"
if __name__ == "__main__":
print(process(42))
print(process("hello"))
print(process([1, 2, 3]))
print(process({"a": 1, "b": 2}))
print(process(3.14))
Output
Integer: 84
String: HELLO
List: 3 items
Dict: 2 keys
Unknown type: float
How it works
The @singledispatch decorator turns a function into a generic function that dispatches on the type of its first argument. Each @process.register(type) decorator binds a specialized implementation for that type. When the function is called, Python selects the most specific registered implementation matching the argument's type. This pattern keeps type-specific logic organized and separate from the base function, improving readability and maintainability.
Common mistakes
- Forgetting the `@singledispatch` decorator on the base function
- Registering the same type multiple times, which overrides the previous implementation
- Calling `process` with a subclass type that has no registration, falling back to the base function
Variations
- Use `@process.register` with a callable for custom types not directly registered
- Use `functools.singledispatchmethod` for dispatching on methods within classes
Real-world use cases
- Implementing polymorphic serialization functions that handle different data types differently.
- Creating a logging function that formats messages based on whether the input is a string, dict, or exception.
- Building a type-aware parser that processes different input formats (e.g., JSON, YAML, CSV) with the same function name.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.