Skip to content

Comment on (Python) Generator Tricks For Systems Programmer (pdf)parent

Comments

Apart from chaining generators, you can write a simple helper to pipe general expressions.

    def pipe(cur_val, *fns):
        """
        Pipes `cur_val` through `fns`.
        ::
            def sqr(x): return x * x

            def negate(x): return -x

        `pipe(5, sqr, negate)`

        is the same as
        ::
            negate(sqr(5))
        """
        for fn in fns:
            cur_val = fn(cur_val)
        return cur_val

I find `pipe(5, sqr, negate)` neater than `negate(sqr(5))`, especially when the nesting is greater than 2.

This is inspired by clojure's threading macro -> and a re-factoring of @fogus's code snippet on stack overflow. He used reduce to implement the loop - though loops can be implemented with reduce, and that's how you generally do it in clojure et al., it isn't idiomatic Python.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.