Last active
May 20, 2020 15:21
-
-
Save fabianvf/acc91f79187053e790f2 to your computer and use it in GitHub Desktop.
Python function composition with a dot 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
| class Composable(object): | |
| ''' A function decorator that allows you to use Haskell style dot notation for function composition ''' | |
| fns = {} | |
| def __init__(self, fn): | |
| self.fn = fn | |
| Composable.fns[fn.__name__] = fn | |
| def __call__(self, *args, **kwargs): | |
| ''' simply calls the function ''' | |
| return self.fn(*args, **kwargs) | |
| def __getattr__(self, other): | |
| ''' The returned function will only be able to be on the left of a composition, for now ''' | |
| return Composable(compose(self.fn, self.fns[other])) | |
| # Examples: | |
| @Composable | |
| def add_17(x): | |
| return x + 17 | |
| @Composable | |
| def subtract_7(x): | |
| return x - 17 | |
| add_17 . subtract_7 (10) == 20 # True | |
| Composable(lambda x: x * 2) . add_17 . add_17 . subtract_7 == 54 # True | |
| # Limitations | |
| # - Anonymous functions can only be on the left hand side of a composition (because they don't have names) | |
| # Ideas: | |
| # - Get the module name and scope when creating a Composable | |
| # - This will allow you to have a function with the same name from two different modules | |
| # - It will also allow you to lookup unknown functions in the module it is being called from |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment