From 3fe8a0d35e9bc2777481e014f9f68195f33aa7ef Mon Sep 17 00:00:00 2001 From: David Arnold Date: Tue, 12 Nov 2024 11:52:19 +0100 Subject: [PATCH] docs: docstring on simple singledipatch util (#28437) --- frappe/model/utils/__init__.py | 41 ++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/frappe/model/utils/__init__.py b/frappe/model/utils/__init__.py index b449d7054f..da6e15ec3e 100644 --- a/frappe/model/utils/__init__.py +++ b/frappe/model/utils/__init__.py @@ -152,6 +152,47 @@ def is_single_doctype(doctype: str) -> bool: def simple_singledispatch(func): + """ + A decorator that implements a simplified version of single dispatch. + + This decorator allows you to define a generic function that can have + different behaviors based on the type of its first argument. It's similar + to Python's functools.singledispatch, but with a simpler implementation. + + Args: + func (callable): The base function to be decorated. + + Returns: + callable: A wrapper function that implements the single dispatch logic. + + The returned wrapper function has a 'register' method that can be used + to register type-specific implementations: + + @wrapper.register(specific_type) + def type_specific_func(arg, ...): + # Implementation for specific_type + + When the wrapped function is called, it dispatches to the most specific + implementation based on the type of the first argument. If no matching + implementation is found, it falls back to the base function. + + Example: + @simple_singledispatch + def func(arg): + print(f"Base implementation for {type(arg)}") + + @func.register(int) + def _(arg): + print(f"Implementation for int: {arg}") + + @func.register(str) + def _(arg): + print(f"Implementation for str: {arg}") + + func(10) # Outputs: Implementation for int: 10 + func("hello") # Outputs: Implementation for str: hello + func([1, 2, 3]) # Outputs: Base implementation for + """ registry = {} def dispatch(arg):