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
import typing
__all__ = ["overloadable"]
class Holder:...
def overloadable(old, /):
holder = Holder()
@functools.wraps(old)
def new(*args, **kwargs):
key = old(*args, **kwargs)
value = holder._data.lookup[key]
ans = value(*args, **kwargs)
return ans
holder._data = new
new.lookup = dict()
new.overload = functools.partial(tool, data=new)
return new
def tool(key=None, **kwargs):
return functools.partial(decorator, key=key, **kwargs)
def decorator(old, /, *, data, key):
typing.overload(old)
data.lookup[key] = old
return data
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.2.tar.gz
(3.3 kB
view details)
Built Distribution
File details
Details for the file overloadable-1.0.2.tar.gz
.
File metadata
- Download URL: overloadable-1.0.2.tar.gz
- Upload date:
- Size: 3.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.12.4
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | ce6ff722c4f863f06071a917d884b2911d42435f8905dfc5832723d8edec1544 |
|
MD5 | f9c3fcbae22f8e296d433f932f30f90c |
|
BLAKE2b-256 | 702efdc50cb9f5c881a0c007d7c95ccf46b7fbb3093509feb081025f96c7b809 |
File details
Details for the file overloadable-1.0.2-py3-none-any.whl
.
File metadata
- Download URL: overloadable-1.0.2-py3-none-any.whl
- Upload date:
- Size: 4.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.12.4
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 98dd3f999732080740d4ed5bb57dda8786c34782fe28f6765257367c7843f31d |
|
MD5 | 276d36ef7c0f68b2bb577ff26320e6ce |
|
BLAKE2b-256 | 53748df12361ea478c85eb92a541a1a6221673592a1e28c3b6660245bb3c9490 |