generic function

In Python, a generic function is a function that operates on different types of data or objects without being explicitly programmed for each type.

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 achieves this through duck typing and the use of polymorphism, which allows functions to handle objects of different class that implement the required method.

In Python, you often create generic functions using function overloading or by using the @singledispatch decorator from the functools module. This decorator allows you to define a function that can behave differently based 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:

Python
>>> 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.

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.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated April 16, 2025