I need to dynamically create a function from a lambda expression that is provided as a string (it will be read from a configuration file). I want to allow the user to also specify a list of modules that can then be used within the lambda expression. For this I need to dynamically load the modules and make them available so that they can be referred to by name within the lambda expression.
The following is a possible implementation of what I want to do:
import importlib
def create_function(lambda_expression, modules=[]):
for module in modules:
globals()[module] = importlib.import_module(module)
function = eval('lambda ' + lambda_expression)
return function
It would be used like this:
f = create_function('x: numpy.clip(x, 0, 1)', ['numpy'])
However, the use of globals() does not seem like a nice solution. Is there a more elegant way to achieve this?