Skip to content

Instantly share code, notes, and snippets.

@jsbueno
Created August 29, 2026 00:40
Show Gist options
  • Select an option

  • Save jsbueno/ff293bf2b80fa02cb86cee574397d888 to your computer and use it in GitHub Desktop.

Select an option

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.
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