Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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