ovld: Overloading Python Functions

0.5.15 · active · verified Mon Apr 13

Ovld is a Python library that provides fast and feature-rich multiple dispatch for functions using type annotations. Unlike Python's built-in `functools.singledispatch`, `ovld` supports dispatching on multiple arguments, custom predicates, and value-based dispatch. It aims to simplify code that would otherwise rely on complex `if-elif` chains or `isinstance` checks for different argument types. The library is actively maintained, with the current version being 0.5.15, and offers performance superior to other multiple dispatch libraries.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic function overloading for different types and argument counts. It also includes an example of recursive dispatch using `recurse`, which is essential for ensuring that nested calls respect `ovld`'s dispatch mechanism and any defined variants.

from ovld import ovld, recurse
from typing import Literal

@ovld
def process(x: str): 
    return f"Processing string: {x!r}"

@ovld
def process(x: int):
    return f"Processing integer: {x}"

@ovld
def process(x: int, y: int):
    return f"Processing two integers: {x}, {y}"

@ovld
def process(x: Literal[0]):
    return "Special case: zero"

# Example of recursive overload
@ovld
def add_nested(x: list, y: list):
    return [recurse(a, b) for a, b in zip(x, y)]

@ovld
def add_nested(x: int, y: int):
    return x + y

assert process("hello") == "Processing string: 'hello'"
assert process(10) == "Processing integer: 10"
assert process(1, 2) == "Processing two integers: 1, 2"
assert process(0) == "Special case: zero"

assert add_nested([1, 2], [3, 4]) == [4, 6]
assert add_nested([1, [2]], [3, [4]]) == [4, [6]]

view raw JSON →