1

I have a pipeline function that takes an arbitrary number of functions as arguments, it returns a single function helper which contain one argument and this function in turn calls the pipeline function with a single argument iteratively. Here is the code:

def pipeline(*funcs):
    def helper(arg):
        for func in funcs:
            result = func(arg)
            arg = result
        return result
    return helper

And here a test case:

fun = pipeline(lambda x: x * 3, lambda x: x + 1, lambda x: x / 2)
print(fun(3)) #should print 5.0

I was reading on a different question about generators and how they can be used to remember previous state here, and was wondering if I could reframe my current pipeline function to use a generator instead. I need to remember the arg for every func call and currently I'm doing that by storing into a variable, however since generators can remember the last state I was wondering if I could use it instead.

moth
  • 1,833
  • 12
  • 29

1 Answers1

1

You could (but absolutely shouldn't) create a side-effect based list-comprehension that uses the walrus-operator:

funcs = [lambda x: x * 3, lambda x: x + 1, lambda x: x / 2]

x = 3
[x := f(x) for f in funcs]
print(x)

What makes this even worse than it already is is the fact that if you use a simple generator instead of the list-comprehension the result is different because it doesn't all get executed before the print.

Or you even force it all in one line like this:

print([x := f(x if i>0 else 3) for i, f in enumerate(funcs)][-1])

I think generally a prettier approach would be to just wrap it into a normal for loop:

x = 3
for f in funcs:
    x = f(x)
print(x)
ewz93
  • 2,444
  • 1
  • 4
  • 12
  • What do you mean by _"side-effect based list-comprehension"_? – cards Jul 23 '22 at 15:37
  • 1
    I mean using a list comprehension only for the effect is has on the variables inside it instead of its return value (e.g. `[print(i) for i in range(5)]`) which to my knowledge is bad style and should be avoided. – ewz93 Jul 23 '22 at 17:14