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.
Project description
Trouting
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:
pip install trouting
The logo of trouting was generated using 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:
from typing import Any, Union
from trouting import trouting
class 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:
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
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 trouting-0.2.0.tar.gz
.
File metadata
- Download URL: trouting-0.2.0.tar.gz
- Upload date:
- Size: 8.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.1 CPython/3.8.13
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 3fa8d36e2e74a0be17eb00c11efe7ff328cad100693c44bf6616e03c5415ef02 |
|
MD5 | a05d1b181f3e1e684a9b9048d4ab6e3b |
|
BLAKE2b-256 | 1da5dd08ac70780892752de414db81695603301667db38a7bc1944fdc4ae12a7 |
File details
Details for the file trouting-0.2.0-py3-none-any.whl
.
File metadata
- Download URL: trouting-0.2.0-py3-none-any.whl
- Upload date:
- Size: 8.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.1 CPython/3.8.13
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | e2e77b584b83a437b2db25543efbb370f916a6607c31d02b05ac282acf3c1aa7 |
|
MD5 | 9bea217a23dfb78cdc5a17f641930654 |
|
BLAKE2b-256 | b8bac0b847484b2dcf33143b161af8ef4d336a5fccdb8d086f2b2174429c217d |