Created
August 29, 2026 00:40
-
-
Save jsbueno/ff293bf2b80fa02cb86cee574397d888 to your computer and use it in GitHub Desktop.
Python: decorator to transform a function into a compositable function using the `&` operator.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import typing | |
| class Compositable: | |
| def __init__(self, func): | |
| self.func_chain = [func] | |
| def __and__(self, other: typing.Callable | Compositable): | |
| cls = type(self) | |
| composite = cls.__new__(cls) | |
| func_chain = composite.func_chain = self.func_chain.copy() | |
| func_chain.append(other) if not isinstance(other, cls) else func_chain.extend(other.func_chain) | |
| return composite | |
| def __call__(self, arg): | |
| result = arg | |
| for func in self.func_chain: | |
| result = func(result) | |
| return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment