Charles R Charles R - 1 year ago 111
Python Question

Better Function Composition in Python

I work in Python. Recently, I discovered a wonderful little package called fn. I've been using it for function composition.

For example, instead of:


with fn, you can write:

(F() >> foo >> bar >> baz)(x) .

When I saw this, I immediately thought of Clojure:

(-> x foo bar baz) .

But notice how, in Clojure, the input is on the left. I wonder if this possible in python/fn.

Answer Source

You can't replicate the exact syntax, but you can make something similar:

def f(*args):
    result = args[0]

    for func in args[1:]:
        result = func(result)

    return result

Seems to work:

>>> f('a test', reversed, sorted, ''.join)
' aestt'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download