SoFunction
Updated on 2024-10-29

Interpretation of python's multimethod package multidistribution

python multimethod package multidistribution

multimethod (a.k.a. multiple dispatch, generic function) is a package of functions provided by python that allows for the implementation ofsingledispatch Similar functionality without having to register multiple times for the same type of return

Usage

1. Use@multimethod Marks the base function (base_function) that handles the object type.

2. Use of specialized functions@<<base_function>>.register ornamental

3, the name of the specialized function is irrelevant, you can directly choose to use _ as the function name

4. Register a function for each type that needs to be processed

(for) instance

@multimethod
def inner_as_dict() -> object:
    """
    The multimethod method, which registers different methods for serializing to a dictionary for different types of keys
    """
    return None
@inner_as_dict.register
def _(element: List[TestData1]) -> [Dict]:
    result = []
    for i in element:
        tmp = asdict(i)
        tmp_list = [ for i in tmp["code"]]
        tmp["msg"] = tmp_list if tmp_list else ["-"]
        (tmp)
    return result
@inner_as_dict.register
def _(element: TestData2) -> List[Dict]:
    result: List[Dict] = []
    if not :
        for message in ():
            single_fail_res = {"item": (",")[0], "result": False}
            (single_fail_res)
    return result
@inner_as_dict.register
def _(element: TestData3) -> Tuple[int, str]:
    verify_result = 0 if  else -1
    verify_message =  if  else "-"
    return dom_result, dom_message
@inner_as_dict.register
def _(element: Union[int, float, bool, str, List, Dict, Tuple]) -> Union[int, float, bool, str, List, Dict, Tuple]:
    return element

You can see the use of multimethod and singledispatch is basically the same, the difference is that, multimethod in the registration function does not need to write the type of processing, and for a variety of types is the same processing, you can not write more than one registration function, more concise and clear.

Python singly-assigned generic functions

conceptual

It allows you to provide multiple implementations of a function that are based on the type of the argument.

realization

Here's an example of how it's used

from functools import singledispatch
@singledispatch
def add(x, y):
    print("Default implementation for integers")
    return x + y
@(int)
def _(x, y):
    print("Implementation for integers")
    return x + y
@(str)
def _(x, y):
    print("Implementation for strings")
    return x + y
print(add(1, 2)) # Output: Default implementation for integers -> 3
print(add("hello", "world")) # Output: Implementation for strings -> helloworld
print(add(1.5, 2.5)) # Output: Default implementation for integers -> 4
print(add("foo", "bar")) # Output: Default implementation for integers -> foobar

In this example, we define a function named add and use the @singledispatch decorator to convert it to a single-assignment generic function.

We provide two implementations for this function:

One default implementation and two implementations specific to integer and string types.

When we call the add function, it will choose the appropriate implementation based on the type of the argument.

If the argument is an integer or floating point number, the default implementation will be called; if the argument is a string, the implementation specific to the string type will be called.

summarize

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.