singledispatch

4.1.2 · active · verified Sat Apr 11

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.

Warnings

Install

Imports

Quickstart

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.

from singledispatch import singledispatch

@singledispatch
def process_data(arg):
    """Default implementation for process_data"""
    return f"Processing generic data: {arg}"

@process_data.register(int)
def _(arg):
    """Process integer data"""
    return f"Processing integer: {arg * 2}"

@process_data.register(list)
def _(arg):
    """Process list data"""
    return f"Processing list: {', '.join(map(str, arg))}"

print(process_data("hello"))
print(process_data(10))
print(process_data([1, 2, 3]))
print(process_data(3.14))

view raw JSON →