Created
April 24, 2018 09:12
-
-
Save alendit/25310703b668ca634408cc16a7e73923 to your computer and use it in GitHub Desktop.
Haskell-like composition for python functions
This file contains 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
def composable(func, contains=None): | |
class Wrapper: | |
@wraps(func) | |
def __call__(self, *args, **kwargs): | |
return func(*args, **kwargs) | |
def __getattr__(self, name): | |
if name in locals(): | |
comp = locals[name] | |
elif name in globals(): | |
comp = globals()[name] | |
else: | |
raise AttributeError() | |
def wrapper(*args, **kwargs): | |
return func(comp(*args, **kwargs)) | |
return composable(wrapper, (contains or []) + [func]) | |
def __repr__(self): | |
contains_str = ', '.join(f.__name__ for f in (contains if contains is not None else []) + [func]) | |
return '<Composable of [{}]>'.format(contains_str) | |
return Wrapper() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment