A basic package that allows to overload functions and class functions dynamically depending on the input types.
Project description
Dynamic Overload
Dynamic Overload is a python package that allows you to overload functions and classes using dynamic dispatch depending on the type of the arguments. This allows you to write more readable code and avoid using isinstance and type checks.
The package also detects collisions between the overloads and warns the user about them without breaking the code. In case of collision, the first overload is used. So, its recomended that you put the most specific overloads first before the more general ones.
Installation
pip install dynamic-overload
Usage
For functions:
from dynamic_overload import overload
from typing import Iterable
@overload
def flatten(x: Iterable[int]) -> Iterable[int]:
return [y for l in x for y in flatten(l)]
@overload
def flatten(x: int) -> Iterable[int]:
yield x
assert list(flatten([1, [2, 3], 4])) == [1, 2, 3, 4]
assert list(flatten(1)) == [1]
For classes:
from dynamic_overload import OverloadMeta
class Integer(metaclass=OverloadMeta):
x: int
def __init__(self, x: int):
self.x = x
def __init__(self, x: str):
self.x = int(x)
def __init__(self, x: float):
self.x = int(x)
assert Integer(1).x == 1
assert Integer('1').x == 1
assert Integer(1.0).x == 1
The package also supports inheritance similar to python abc module. So the previous example can be rewritten as:
from dynamic_overload import Overload
class Integer(Overload):
x: int
def __init__(self, x: int):
self.x = x
def __init__(self, x: str):
self.x = int(x)
def __init__(self, x: float):
self.x = int(x)
assert Integer(1).x == 1
assert Integer('1').x == 1
assert Integer(1.0).x == 1
License
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
Built Distribution
File details
Details for the file dynamic_overload-0.1.0.tar.gz
.
File metadata
- Download URL: dynamic_overload-0.1.0.tar.gz
- Upload date:
- Size: 8.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.10.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | a51f8175af6022700c895fcc87d6d16e4968a18856901b167e5052b0f58f06de |
|
MD5 | 8297b8cd2a98d75a97fbbcb256c650a4 |
|
BLAKE2b-256 | 5d045c7480d1aa30d38c87e1dcbc0fc68e47400bb2b7a7b8343201d715e72158 |
File details
Details for the file dynamic_overload-0.1.0-py3-none-any.whl
.
File metadata
- Download URL: dynamic_overload-0.1.0-py3-none-any.whl
- Upload date:
- Size: 6.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.10.0
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 8ce6318c567e589f9dbdc0ca197c1fdb9b1a8198dbae37dc7061d311c88c2419 |
|
MD5 | 93d0620ec1f2b0da91bc5d10c2097613 |
|
BLAKE2b-256 | 8be9bc842e6431ab98c0e80f9c4f29be77093476a27e1df570af9fa01a071306 |