Python functools singledispatch() Function
The Python singledispatch() function perform operations regardless of any datatype. If we want a function to behave differently based on the argument type, this decorator allows us to write functions that dispatch operations based on the type of the argument.
If the implementations are denoted with types then the decorator automatically determines the argument type. Otherwise, the type itself is passed as an argument to the decorator.
Syntax
Following is the syntax for the singledispatch() function.
@singledispatch
Parameters
The singledispatch() decorator is used on this function to handle the default case.
Return Value
This decorator returns the specific type of a function to handle the default case.
Example 1
This code uses singledispatch() function to determine different data types. This function processes specifies integers, strings, and other types uniquely.
from functools import singledispatch
@singledispatch
def process_data(data):
return f"processing for {data}"
@process_data.register(int)
def _(data):
return f"integer: {data}"
@process_data.register(str)
def _(data):
return f"string: {data}"
print(process_data(25))
print(process_data("Welcome to Tutorialspoint"))
print(process_data([4, 3, 6]))
Output
The result is generated as follows −
integer: 25 string: Welcome to Tutorialspoint processing for [4, 3, 6]
Example 2
In the below example, we are managing different data types using singledispatch() function. This function has specific implementations for list and dictionaries.
from functools import singledispatch
@singledispatch
def process_data(data): return f"processing for {data}"
@process_data.register(int)
def _(data): return f"integer: {data}"
@process_data.register(float)
def _(data): return f"float: {data}"
print(process_data(10))
print(process_data(10.5))
print(process_data(1.22))
Output
The code is generated as follows −
integer: 10 float: 10.5 float: 1.22
Example 3
Here, we are specifying the different collection types in this singledispatch() function. The process_data function is decorated with this function to determine data types.
from functools import singledispatch
@singledispatch
def process_data(data): return f"processing for {data}"
@process_data.register(list)
def _(data): return f"list: {data}"
@process_data.register(dict)
def _(data): return f"dict: {data}"
print(process_data([4, 7, 9, 3]))
print(process_data({"key": "value"}))
print(process_data(64))
Output
The output is obtained as follows −
list: [4, 7, 9, 3]
dict: {'key': 'value'}
processing for 64