Is there a function in Python that would do this:
JavaScript
x
2
1
val = f3(f2(f1(arg)))
2
by typing this (for example):
JavaScript
1
2
1
val = chainCalling(arg,f3,f2,f1)
2
I just figured, since python is (arguably) a functional language the function I’m looking for will make syntax brighter
Advertisement
Answer
Use the reduce()
function to chain calls:
JavaScript
1
4
1
from functools import reduce
2
3
val = reduce(lambda r, f: f(r), (f1, f2, f3), arg)
4
I used the forward-compatible functools.reduce()
function; in Python 3 reduce()
is no longer in the built-in namespace.
This can also be made a separate function, of course:
JavaScript
1
8
1
from functools import reduce
2
3
def chain(*funcs):
4
def chained_call(arg):
5
return reduce(lambda r, f: f(r), funcs, arg)
6
7
return chained_call
8