The `singledispatch` library provides a standalone implementation of the `functools.singledispatch` decorator, which allows for generic functions to have different behaviors based on the type of their first argument. Originally a backport for older Python versions, the PyPI package currently targets Python 3.9+ and is actively maintained with regular releases, as evidenced by recent version updates.
pip install singledispatchVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to create a single-dispatch generic function using the `@singledispatch` decorator. It defines a default implementation and then registers specific implementations for `int` and `list` types. When called, the appropriate function is dispatched based on the type of the first argument.
For new projects on Python 3.4+, consider using `from functools import singledispatch`. If you specifically need this package, ensure you import from `singledispatch`.
Upgrade your Python environment to 3.9+ or pin `singledispatch` to a version older than 4.0.0 (e.g., `~=3.7`) if you need to support Python 3.8.
If you require dispatching on multiple arguments or keyword arguments, you will need to implement a custom solution or use a third-party library designed for multiple dispatch.
pip install singledispatch
from singledispatch import singledispatch
from singledispatch import singledispatch
@singledispatch
def my_function(arg):
# Default implementation
pass
@my_function.register(int)
def _(arg: int):
return arg + 1from singledispatch import singledispatch
@singledispatch
def my_function(arg):
# This is a callable function
passNo dependency data recorded yet.