docs: docstring on simple singledipatch util (#28437)
This commit is contained in:
parent
7d95f4577c
commit
3fe8a0d35e
1 changed files with 41 additions and 0 deletions
|
|
@ -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 <class 'list'>
|
||||
"""
|
||||
registry = {}
|
||||
|
||||
def dispatch(arg):
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue