Create an overloaded function around a core choosing function.
Project description
Overview
Create an overloaded function around a core choosing function.
Installation
To install overloadable, you can use pip. Open your terminal and run:
pip install overloadable
Implementation
import functools
from typing import *
__all__ = ["overloadable"]
class Holder: ...
def identity(old: Any, /) -> Any:
return old
def overloadable(
old: Callable,
/,
) -> Callable:
holder = Holder()
try:
func = old.__func__
except AttributeError:
func = old
bind = identity
else:
bind = type(old)
@bind
@functools.wraps(func)
def new(*args, **kwargs) -> Any:
key = func(*args, **kwargs)
value = holder._data.lookup[key]
ans = value(*args, **kwargs)
return ans
holder._data = new
new.lookup = dict()
new.overload = functools.partial(
overloadtool,
bind=bind,
data=new,
)
return new
def overloaddecorator(
old: Callable,
/,
*,
bind: Callable,
data: Any,
key: Hashable,
) -> Any:
data.lookup[key] = old
overload(bind(old))
return data
def overloadtool(
key: Hashable = None,
**kwargs,
) -> Any:
return functools.partial(
overloaddecorator,
key=key,
**kwargs,
)
Example
from overloadable import overloadable
class Bar:
def __init__(self, addon) -> None:
self.addon = addon
@overloadable
def foo(self, x):
if type(x) is int:
return "int"
@foo.overload("int")
def foo(self, x):
return x * x + self.addon
@foo.overload() # key=None
def foo(self, x):
return str(x)[::-1]
bar = Bar(42)
print(bar.foo(1)) # prints 43
print(bar.foo(3.14)) # prints 41.3
print(bar.foo("baz")) # prints zab
License
This project is licensed under the MIT License.
Links
Credits
Author: Johannes
Thank you for using overloadable!
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
overloadable-1.0.5.tar.gz
(3.8 kB
view details)
Built Distribution
File details
Details for the file overloadable-1.0.5.tar.gz
.
File metadata
- Download URL: overloadable-1.0.5.tar.gz
- Upload date:
- Size: 3.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.12.5
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 2d96707764d058770b0efe967abc0102dfa16a52357c0e17216306df2ca15f7f |
|
MD5 | fd4f23c2521d405a93b6e27392416321 |
|
BLAKE2b-256 | 49d156006460b0f88b8dd4c55027f3c25b32b8b74b27e985f08bf3e181a3dca8 |
File details
Details for the file overloadable-1.0.5-py3-none-any.whl
.
File metadata
- Download URL: overloadable-1.0.5-py3-none-any.whl
- Upload date:
- Size: 5.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.12.5
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 4c348447aa171bca812d88d677d7b07c8d86370b85d422ece54cd16b83047a7f |
|
MD5 | ba65378c350b1c9116335c19631a319b |
|
BLAKE2b-256 | 453bc7b531139c14e4b498cc75aa7a9bed07b80773d948f1c74ccef8ca8fb869 |