footings.utils.dispatch_function¶
-
dispatch_function
(key_parameters: Tuple, default_function: Optional[Callable] = None)[source]¶ Transform a function into a generic dispatch function.
A dispatch function operates similar to functools.singledispatch where a generic function is recorded and additional functions can be registered and called based on passed arguments. However, functools.singledispatch calls a registered function based on the type of the first argument. Dispatch function calls a registered function based on the key word arguments assigned when registering a function. If a registered function does not exist for the passed parameters, the default functions is called. To force only registerd functions to be used, have the default function raise NotImplementedError.
A dispatch_function is a useful function to replace a block of if else statements that call different functions.
- Parameters
key_parameters (tuple) – A tuple of the paramters to use as.
default_function (callable) – The default function to use when the function is called and a regestered function cannot be found. function docstring and signature sourced.
See also
functools.singledispatch
- Examples
>>> @dispatch_function(key_parameters=("key",)) >>> def dispatch(key): >>> return "default" >>> >>> @dispatch.register(key="x") >>> def _(): >>> return "x" >>> >>> @dispatch.register(key="y") >>> def _(): >>> return "y" >>> >>> assert dispatch(key="x") == "x" >>> assert dispatch(key="y") == "y" >>> assert dispatch(key="z") == "default" >>> assert dispatch(key=None) == "default"