overloadable
Introduction

This project allows to create an overloaded function around a core choosing function.

Installation
Features
class overloadable.Overloadable(dispatch: Any)

This class is meant as a decorator for a dispatch. Its overloads can be added with overload.

dispatch: Any

This attribute holds the dispatch.

lookup: Any

This attribute holds all the overloads under their respective keys.

overload(key: Any = None) -> functools.partial
This method returns a decorator that adds the decorated overload into the lookup under the given key.
overloadable.overloadable

This module variable is an alias for Overloadable included for legacy.

Example
from overloadable import Overloadable

class Bar:

    addon: Any

    def __init__(self: Self, addon: Any) -> None:
        self.addon = addon

    @Overloadable
    def foo(self: Self, x: Any) -> Optional[str]:
        if type(x) is int:
            return "int"

    @foo.overload("int")
    def foo(self: Self, x: int) -> Any:
        return x * x + self.addon

    @foo.overload() # key=None
    def foo(self: Self, x: str) -> str:
        return str(x)[::-1]

bar: Bar = Bar(42)
print(bar.foo(1)) # prints 43
print(bar.foo(3.14)) # prints 41.3
print(bar.foo("baz")) # prints zab
from overloadable import Overloadable

class Bar:

    @Overloadable
    @staticmethod
    def foo(x: Any) -> int | str:
        return type(x)

    @foo.overload(int)
    def foo(x: int) -> int:
        return x ** 2

    @foo.overload(str)
    def foo(x: str) -> str:
        return str(x)[::-1]

bar: Bar = Bar()
print(bar.foo(5)) # prints 25
print(bar.foo("baz")) # prints zab
print(Bar.foo(5)) # prints 25
print(Bar.foo("baz")) # prints zab
Testing
License
Impressum