Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/soldni/trouting
Type Routing (trouting) is a decorator that selects the right method in a class based on the input data type
https://github.com/soldni/trouting
Last synced: 6 days ago
JSON representation
Type Routing (trouting) is a decorator that selects the right method in a class based on the input data type
- Host: GitHub
- URL: https://github.com/soldni/trouting
- Owner: soldni
- License: apache-2.0
- Created: 2022-09-03T00:02:01.000Z (about 2 years ago)
- Default Branch: main
- Last Pushed: 2023-01-17T01:27:00.000Z (almost 2 years ago)
- Last Synced: 2024-09-17T16:11:06.650Z (about 2 months ago)
- Language: Python
- Homepage: https://pypi.org/project/trouting
- Size: 1.98 MB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Trouting
![](https://github.com/soldni/trouting/raw/main/static/logo.png)
Trouting (short for Type Routing) is a simple class decorator that allows to define multiple interfaces for a method that behave differently depending on input types.
To install for PyPI trouting, run:
```bash
pip install trouting
```The logo of trouting was generated using [Stable Diffusion](https://github.com/CompVis/stable-diffusion) with prompt *"A Kandinsky painting titled The Trout Who Routes"* and slightly edited by the author.
## Example
Imagine you want to define a class whose method behaves differently depending on whether the input is a string or an integer. You can do this with trouting as follows:
```python
from typing import Any, Union
from trouting import troutingclass MyClass:
@trouting
def add_one(self, a: Any) -> Any:
# fallback method
raise TypeError(f"Type {type(a)} not supported")@add_one.add_interface(a=(int, float))
def add_one_int(self, a: Union[int, float]) -> float:
# a is an int or float
return float(a + 1)@add_one.add_interface(a=str)
def add_one_str(self, a: str) -> str:
# a is a str
return a + "1"
```Now, when using `MyClass`, the method `add_one` will behave differently depending on the input type:
```python
my_class = MyClass()
my_class.add_one(1) # returns 2.0
my_class.add_one("1") # returns "11"
my_class.add_one([1]) # raises TypeError
```