Content · Programming · Python

Python functools.singledispatch() Decorator: Usage and Examples

Select a function implementation based on the first argument type.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Select a function implementation based on the first argument type.

What You Will Learn


singledispatch creates a generic function with type-specific implementations registered through @function.register. Dispatch uses the runtime type of the first argument, not all arguments.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

from functools import singledispatch
@singledispatch
def describe(value):
    return 'other'
@describe.register
def _(value: int):
    return 'integer'
print(describe(4))
print(describe('four'))

How the Example Works


  • The imports provide the standard-library tools used in the demonstration: functools.
  • The definitions describe, _ separate the main steps into named components; calls to those components drive the example.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

Expected output from the example:

integer
other

When You Would Use This


These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.

Practice: Modify the Code


Register handlers for int and list and test subclasses.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Expecting singledispatch to choose overloads using a second argument or a return annotation.
  • Overlooking this documented constraint: dispatch uses the runtime type of the first argument, not all arguments.

Key Takeaways


  • Select a function implementation based on the first argument type.
  • singledispatch creates a generic function with type-specific implementations registered through @function.register.
  • Apply this operation only after checking the assumptions and input conditions shown in the example.
Share this resourceSend this page to someone who may find it useful.