Dynamic generation of Python function with given parameter names
I would like to create functions in my Python3 code, making use of data supplied during run-time. I'm stuck on how I can write a function along the lines of
def foo(varname1, varname2):
return varname1 + varname2
where the strings varname1
and varname2
that give the parameter names are specified as arguments to some constructor function, e.g.:
def makeNewFooFunc(varname1, varname2):
# do magic
return foo
fooFunc = makeNewFooFunc('first', 'second')
print(fooFunc(first=1, second=2))
# should return 3
what would be the #do magic
step? Is this a job for eval
, or is there an alternative?
1 answer
-
answered 2018-07-12 07:58
Ilya Miroshnichenko
You don't need to write a function like that. just use **kwargs
def foo_func(**kwargs): return sum(kwargs.values()) foo_func(any_name=1, any_name_2=2)
but if you still need to do what you want, you can try
def make_new_func(var_name_1, var_name_2): def foo(**kwargs): # make sure in kwargs only expected parameters assert set(kwargs) == {var_name_1, var_name_2} return kwargs[var_name_1] + kwargs[var_name_2] return foo foo_func = make_new_func('a', 'b') foo_func(a=1, b=2)