Functional composition in python

Dmitry Groshev lambdadmitry at gmail.com
Sat Aug 28 13:30:39 EDT 2010


Hello all. Some time ago I wrote a little library:
http://github.com/si14/python-functional-composition/ , inspired by
modern functional languages like F#. In my opinion it is quite useful
now, but I would like to discuss it.
An example of usage:

import os
from pyfuncomp import composable, c, _

def comment_cutter(s):
    t = s.find("#")
    return s if t < 0 else s[0:t].strip()

@composable #one can use a decorator to make a composable function
def empty_tester(x):
    return len(x) > 0 and x[0] != "#"

path_prefix = "test"

config_parser = (c(open) >>  #or use a transformer function
                 c(str.strip).map >> #"map" acts like a function modifier
                 c(comment_cutter).map >>
                 empty_tester.filter >> #so does "filter"
                 c(os.path.join)[path_prefix, _].map) #f[a, _, b] is
used to make a partial.
                                                    #f[a, foo:bar,
baz:_] is also correct

print config_parser("test.txt")
print (c("[x ** %s for x in %s]")[2, _] << c(lambda x: x * 2).map)([1, 2, 3])

Any suggestions are appreciated.



More information about the Python-list mailing list