Python singledispatch()
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.
Syntax
The singledispatch() function is included in the functools module:
@functools.singledispatchdef 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@singledispatchdef 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 callsprocess(10)process("Hello")
Here is the output for this code:
Processing an integer: 10Processing 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:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve 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