Charles R Charles R - 2 months ago 22
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:

baz(bar(foo(x))))


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

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'
Comments