Skip to content

Instantly share code, notes, and snippets.

@alendit
Created April 24, 2018 09:12
Show Gist options
  • Save alendit/25310703b668ca634408cc16a7e73923 to your computer and use it in GitHub Desktop.
Save alendit/25310703b668ca634408cc16a7e73923 to your computer and use it in GitHub Desktop.
Haskell-like composition for python functions
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