docs: docstring on simple singledipatch util (#28437)

This commit is contained in:
David Arnold 2024-11-12 11:52:19 +01:00 committed by GitHub
parent 7d95f4577c
commit 3fe8a0d35e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -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):