Python utility to implement protocols with pure functions
Project description
functiongroup
FunctionGroup is a Python utility designed to simplify the implementation of protocols using pure functions. If you've ever found yourself creating classes solely to group related functions when implementing protocols, this package offers an elegant solution.
Example
Let's consider a scenario where you have a protocol for saving and loading dictionaries, like the DictIO
example below:
from typing import Protocol
class DictIO(Protocol):
def save_dict(self, dict_: dict[str, str], file_name: str) -> None:
...
def load_dict(self, file_name: str) -> dict[str, str]:
...
Traditionally, you'd implement this protocol by creating a class:
import json
class JsonDictIO(DictIO):
def save_dict(self, dict_: dict[str, str], file_name: str) -> None:
with open(file_name, "w") as f:
json.dump(dict_, f)
def load_dict(self, file_name: str) -> dict[str, str]:
with open(file_name) as f:
return json.load(f)
dict_io = JsonDictIO()
However, you may wonder why you need a class when you're not modifying its state or using any dunder methods. You're essentially using the class to group related functions, so why not use a FunctionGroup
instead?
from functiongroup import FunctionGroup
json_dict_io = FunctionGroup()
@json_dict_io.register
def save_dict(dict_: dict[str, str], file_name: str) -> None:
with open(file_name, "w") as f:
json.dump(dict_, f)
@json_dict_io.register
def load_dict(file_name: str) -> dict[str, str]:
with open(file_name) as f:
return json.load(f)
dict_io = json_dict_io()
This approach encourages a more functional code style and provides all the advantages of pure functions.
Project details
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 functiongroup-0.1.0.tar.gz
.
File metadata
- Download URL: functiongroup-0.1.0.tar.gz
- Upload date:
- Size: 2.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: poetry/1.6.1 CPython/3.11.6 Linux/6.2.0-1014-azure
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | ee3204d459c0b8f3a2c1da0c7d1081efd7414561b1124c3f82f61778514cc290 |
|
MD5 | 13c3b9de6873694a2f1f8c0d46ca2d0d |
|
BLAKE2b-256 | 2e3fab98bafaf02ff5c1ad19be32e74c3a73627b96073044810ad476b3af6c68 |
File details
Details for the file functiongroup-0.1.0-py3-none-any.whl
.
File metadata
- Download URL: functiongroup-0.1.0-py3-none-any.whl
- Upload date:
- Size: 3.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: poetry/1.6.1 CPython/3.11.6 Linux/6.2.0-1014-azure
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | a05b873120e6905075f1143a520c0c3232f32a0b0c4c48c54701341cfd9475b8 |
|
MD5 | 91f311d897d31bf4ba3ba354d0b9979e |
|
BLAKE2b-256 | 2f74335b4271c751e2539d96f810927ba0b45947de128d8b57c9eeccbd90b97a |