Create a function at runtime that has a specific number of arguments in python

Viewed 43

Is it possible to create a function with a fixed number of arguments at runtime?

I need to create a function that composes two functions, so that I get f_new(x,a,b,c,d,e) = f_1(x,a,b) + f_2(x,c,d,e) for two arbitrary functions f_1 and f_2. Using an approach like

from inspect import signature
def combine(f_1,f_2):
    arg_len_1 = len(signature(f_1).parameters) - 1
    arg_len_2 = len(signature(f_2).parameters) - 1
    def combined(x,*args):
        return f_1(x,args[:arg_len_1]) + f_2(x,args[arg_len_1:arg_len_2])
    return combined

does not work for me, as you can't apply it twice because the number of arguments gets lost in the process.

Is there any way to achieve this in python without using eval() or is that the only option?

0 Answers
Related