passing functions and its arguments to another function

后端 未结 3 1684
醉话见心
醉话见心 2021-01-16 15:38

I have tree types of sub-functions:

  • one without any parameters (arguments),
  • second with one parameter
  • third with multiple parameters (tuple
3条回答
  •  执念已碎
    2021-01-16 16:06

    by goolging 'python determine number of args for passed function' I found How can I find the number of arguments of a Python function?

    I'm pretty sure you don't want the **kwars key, value syntax so I use a func_list regular arg and *args

    from inspect import signature
    
    
    def function_results_sum(func_list, *args):
    
        arg_gen = (e for e in args)
    
        return sum([func(*(next(arg_gen)
                           for _ in range(len(signature(func).parameters))))
                   for func in func_list])
    
    function_results_sum([no_arg, ident, mult], 7,8,9)
    84  
    

    the input can be made flatter by parsing *args for Functions and (presumed) arguments (anything not Type Function)

    from inspect import signature
    import types
    
    
    def function_results_sum(*args):
    
        func_gen = (e for e in args if isinstance(e, types.FunctionType))
    
        arg_gen = (e for e in args if not isinstance(e, types.FunctionType))
    
        return sum(func(*(next(arg_gen)
                           for _ in range(len(signature(func).parameters))))
                   for func in func_gen)
    
    function_results_sum(no_arg, ident, mult, 10,6,90)
    555
    

    order of functions and order of args are important, but separately, can be interleaved:

    function_results_sum(no_arg, 10, ident, 6, 90, mult)
    Out[399]: 555
    

提交回复
热议问题