This project allows to create an overloaded function around a core choosing function.
This class is meant as a decorator for a dispatch.
Its overloads can be added
with overload.
This attribute holds the dispatch.
This attribute holds all the overloads under their respective keys.
lookup
under the given key.
This module variable is an alias for Overloadable included for legacy.
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