Composing functions in python

前端 未结 12 1228
北荒
北荒 2020-11-27 03:56

I have an array of functions and I\'m trying to produce one function which consists of the composition of the elements in my array. My approach is:

def compo         


        
12条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 04:24

    The most reliable implementation I have found is in the 3rd party library toolz. The compose function from this library also deals with docstring for the composition of functions.

    The source code is freely available. Below is a simple example of usage.

    from toolz import compose
    
    def f(x):
        return x+1
    
    def g(x):
        return x*2
    
    def h(x):
        return x+3
    
    res = compose(f, g, h)(5)  # 17
    

提交回复
热议问题