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.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 12 views 0 copies

Python code

28 lines
Python 3.9+
from 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

stdout
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

  1. Use `@process.register` with a callable for custom types not directly registered
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.