Skip to content

Instantly share code, notes, and snippets.

@johntyree
Created April 18, 2014 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johntyree/11062517 to your computer and use it in GitHub Desktop.
Save johntyree/11062517 to your computer and use it in GitHub Desktop.
Composable functions... kind of
#!/usr/bin/env python
# coding: utf8
# GistID: 11062517
from __future__ import division
import functools
import inspect
class composable(object):
def __init__(self, f):
if not isinstance(f, list):
f = [f]
self.funcs = f
def __call__(self, *args, **kwargs):
f = self.funcs[-1]
result = f(*args, **kwargs)
print result
for f in self.funcs[-2::-1]:
result = f(result)
print result
return result
def __getattr__(self, g_string):
if g_string == '_':
print "partial(apply, {})".format(self.funcs[-1])
self.funcs[-1] = functools.partial(apply, self.funcs[-1])
return self
fr = inspect.currentframe()
while fr:
if g_string in fr.f_locals:
g = fr.f_locals[g_string]
# Flatten it here for turbo speeds!
if isinstance(g, composable):
funcs = g.funcs
else:
funcs = [fr.f_locals[g_string]]
val = composable(self.funcs + funcs)
return val
fr = fr.f_back
else:
raise NameError("name {!r} not defined".format(g_string))
@composable
def to_tuple(a):
return (a, a)
@composable
def two_args(a, b):
return a + b
@composable
def tuple_args(t):
return (len(t), t)
@composable
def nop(x):
return x
def main():
print tuple_args . to_tuple . two_args(2, 3)
print tuple_args . to_tuple . two_args . _ . nop((2, 3))
return 0
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment