Skip to content

Instantly share code, notes, and snippets.

@lyndsysimon
Last active September 29, 2016 18:04
Show Gist options
  • Save lyndsysimon/96977376ff5a743b737a3a30b607e6c8 to your computer and use it in GitHub Desktop.
Save lyndsysimon/96977376ff5a743b737a3a30b607e6c8 to your computer and use it in GitHub Desktop.
Python functional composition
class composable:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
def __or__(self, other):
return lambda *args, **kwargs: self(other(*args, **kwargs))
def __ror__(self, other):
return lambda *args, **kwargs: other(self(*args, **kwargs))
@composable
def a(x):
return x + x
@composable
def b(x):
return '{0}{0}'.format(x)
@composable
def c(x):
return '-{}-'.format(x)
d = c | b | a
d(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment