Search code examples
pythonfunctional-programming

Is there something like the threading macro from Clojure in Python?


In Clojure I can do something like this:

(-> path
      clojure.java.io/resource
      slurp
      read-string)

instead of doing this:

(read-string (slurp (clojure.java.io/resource path)))

This is called threading in Clojure terminology and helps getting rid of a lot of parentheses.

In Python if I try to use functional constructs like map, any, or filter I have to nest them to each other. Is there a construct in Python with which I can do something similar to threading (or piping) in Clojure?

I'm not looking for a fully featured version since there are no macros in Python, I just want to do away with a lot of parentheses when I'm doing functional programming in Python.

Edit: I ended up using toolz which supports pipeing.


Solution

  • Here is a simple implementation of @deceze's idea (although, as @Carcigenicate points out, it is at best a partial solution):

    import functools
    def apply(x,f): return f(x)
    def thread(*args):
        return functools.reduce(apply,args)
    

    For example:

    def f(x): return 2*x+1
    def g(x): return x**2
    thread(5,f,g) #evaluates to 121