Python singledispatch()

Anonymous contributor's avatar
Anonymous contributor
Published Aug 27, 2025
Contribute to Docs

In Python, functools.singledispatch is a decorator that converts a function into a generic function(a type single function that can perform different actions depending on the data type of the input it receives) with behavior varying by the type of its first argument. It simplifies type-specific logic by allowing separate implementations to be registered instead of relying on multiple if statements.

  • Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
    • Includes 27 Courses
    • With Professional Certification
    • Beginner Friendly.
      95 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

The singledispatch() function is included in the functools module:

@functools.singledispatch
def func(arg, ...):
...

Parameters:

  • Takes a single callable (function) as the argument when used as a decorator.
  • The decorated function must accept at least one argument (the one whose type determines dispatch).

Return value:

  • singledispatch() returns a single-dispatch generic function object.
  • Additional implementations can be registered for different types using the .register(type) method on the generic function.

Example 1: Creat a generic function process

This example uses the singledispatch decorator to handle different input types in a custom way:

from functools import singledispatch
@singledispatch
def process(value):
print("Processing:", value)
@process.register(int)
def _(value):
print("Processing an integer:", value)
@process.register(str)
def _(value):
print("Processing a string:", value)
# Function calls
process(10)
process("Hello")

Here is the output for this code:

Processing an integer: 10
Processing a string: Hello

Codebyte Example: Basic type-based greeting

This minimal example shows how singledispatch() changes behavior based on the type of its first argument:

Code
Output

All contributors

Contribute to Docs

Learn Python on Codecademy

  • Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
    • Includes 27 Courses
    • With Professional Certification
    • Beginner Friendly.
      95 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours