generic function
In Python, a generic function is a function composed of multiple implementations of the same operation for different types. A dispatch algorithm picks which implementation runs for a given call, based on the type of the argument or arguments passed in.
Generic functions allow you to write flexible and reusable code by defining operations that can work with many different data types, as long as they satisfy certain conditions or interfaces. Python implements generic functions through dispatch: each supported type gets its own registered implementation, and Python selects the matching one at call time. When that choice depends on the type of a single argument, it’s called single dispatch.
This differs from duck typing, which ignores an object’s type altogether, though both are ways of achieving polymorphism.
In Python, you create generic functions with the @singledispatch decorator from the functools module, which lets you register overloaded implementations for different argument types.
This decorator allows you to define a function that can behave differently depending on the type of its first argument. It provides a simple way to extend the behavior of a function without modifying its original code, thus adhering to the open/closed principle in software design.
Example
Here’s a quick example of a generic function using @singledispatch:
>>> from functools import singledispatch
>>> @singledispatch
... def process(data):
... print(f"Processing {data}")
...
>>> @process.register
... def _(data: int):
... print(f"Processing an integer: {data}")
...
>>> @process.register
... def _(data: list):
... print(f"Processing a list with {len(data)} elements")
...
>>> process("Hello, World!")
Processing Hello, World!
>>> process(10)
Processing an integer: 10
>>> process([1, 2, 3])
Processing a list with 3 elements
In this example, process() is a generic function that performs different actions depending on the type of input data. The @singledispatch decorator lets you define the base implementation, which is called when the input data type doesn’t have a dedicated implementation. Then, you register alternative implementations to handle other types, like integers and lists.
Related Resources
Tutorial
Providing Multiple Constructors in Your Python Classes
In this step-by-step tutorial, you'll learn how to provide multiple constructors in your Python classes. To this end, you'll learn different techniques, such as checking argument types, using default argument values, writing class methods, and implementing single-dispatch methods.
For additional information on related topics, take a look at the following resources:
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.
By Leodanis Pozo Ramos • Updated Sept. 21, 2026