Today is Single-dispatch generic functions (PEP-443). Generic functions are often translated as generic functions, but they are used slightly differently depending on the language. In Python, it seems to be used to mean "give the same name to multiple functions that behave differently depending on the argument type".
I don't understand at all even if I write, so I'll give you an example. Consider a function whose output differs depending on the argument type. It looks like this without using generic functions.
def print_func(arg):
arg_type = type(arg)
if arg_type is int:
print("found integer:", arg)
elif arg_type is list:
print("found list:", arg)
else:
print("found something:", arg)
print_func(1)
print_func(['a','b','c'])
print_func(1.23)
Process while checking the type of the input argument one by one with the if statement. The execution result is as follows.
found integer: 1
found list: ['a', 'b', 'c']
found something: 1.23
If you write this with Single-dispatch generic functions, it will be like this.
from functools import singledispatch
@singledispatch
def print_func(arg):
print("found something:", arg)
@print_func.register(int)
def _(arg):
print("found integer:", arg)
@print_func.register(list)
def _(arg):
print("found list:", arg)
print_func(1)
print_func(['a','b','c'])
print_func(1.23)
It feels like modifying the base function with a single ispatch decorator and adding processing for each type to it using the register method. Which one is better is subtle, but if the processing for each type becomes longer, this may be cleaner than putting it in one if statement.
The result is the same as above, so it is omitted.
But I can't think of any use. It is common to see a certain value and dispatch it, for example, parsing of such a data group because the format of the data that follows can be known from the value of Header. In such a case, it is often realized by preparing a Dict that subtracts a function from the value, but this is a type.
Recommended Posts