For my own entertainment, I was wondering how to achieve the following:
functionA = make_fun([\'paramA\', \'paramB\'])
functionB = make_fun([\'arg1\', \'arg2\',
You can use exec to construct the function object from a string containing Python code:
def make_fun(parameters):
exec("def f_make_fun({}): pass".format(', '.join(parameters)))
return locals()['f_make_fun']
Example:
>>> f = make_fun(['a', 'b'])
>>> import inspect
>>> print(inspect.signature(f).parameters)
OrderedDict([('a', ), ('b', )])
If you want more functionality (e.g., default argument values), it's a matter of adapting the string that contains the code and having it represent the desired function signature.
Disclaimer: as pointed out below it's important that you verify the contents of parameters and that the resulting Python code string is safe to pass to exec. You should construct parameters yourself or put restrictions in place to prevent the user from constructing a malicious value for parameters.