Is there a call method in Python?

Is there a function in Python that will do this:

val = f3(f2(f1(arg)))

typing this (for example):

val = chainCalling(arg,f3,f2,f1)

I just realized, since python is a (possibly) functional language, the function I'm looking for will make the syntax brighter

+7
source share
3 answers

Use the function for call chains: reduce()

from functools import reduce

val = reduce(lambda r, f: f(r), (f1, f2, f3), arg)

I used the forward-compatible functionfunctools.reduce() ; in Python 3 is reduce()no longer in the built-in namespace.

+10
source

You can use reduce()functool - as Martyn suggested, or you can just write it yourself:

def chainCalling(arg, *funcs):
    if len(funcs) > 0:
        return chainCalling(funcs[0](arg), funcs[1:])
    return arg

, , , , Martijn:

def chainCalling(arg, *funcs):
    result = arg
    for f in funcs:
        result = f(result)
    return result

, , :

chainCalling(arg, f1, f2, f3)
+2

It may be a little late, but try my solution below. chain_funcessentially creates a new wrapper function that calls all the underlying functions in the chain when called at run time.

def chain_func(*funcs):
    def _chain(*args, **kwargs):
        cur_args, cur_kwargs = args, kwargs
        ret = None
        for f in reversed(funcs):
            cur_args, cur_kwargs = (f(*cur_args, **cur_kwargs), ), {}
            ret = cur_args[0]
        return ret

    return _chain
0
source

Source: https://habr.com/ru/post/1622918/


All Articles