Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a list of Python functions in order elegantly

I have an input value val and a list of functions to be applied in the order:

funcs = [f1, f2, f3, ..., fn]

How to apply elegantly and not writing

fn( ... (f3(f2(f1(val))) ... )

and also not using for loop:

tmp = val
for f in funcs:
    tmp = f(tmp)

Thanks Martijn for the awesome answer. There's some reading I found: https://mathieularose.com/function-composition-in-python/ .

like image 448
Viet Avatar asked Aug 24 '16 12:08

Viet


1 Answers

Use the reduce() function:

# forward-compatible import
from functools import reduce

result = reduce(lambda res, f: f(res), funcs, val)

reduce() applies the first argument, a callable, to each element taken from the second argument, plus the accumulated result so far (as (result, element)). The third argument is a starting value (the first element from funcs would be used otherwise).

In Python 3, the built-in function was moved to the functools.reduce() location; for forward compatibility that same reference is available in Python 2.6 and up.

Other languages may call this folding.

If you need intermediate results for each function too, use itertools.accumulate() (only from Python 3.3 onwards for a version that takes a function argument):

from itertools import accumulate, chain
running_results = accumulate(chain(val, funcs), lambda res, f: f(res))
like image 66
Martijn Pieters Avatar answered Sep 27 '22 20:09

Martijn Pieters