1

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?

1
  • can you setup your configuration file differently, like as actual code, and then import the module? Commented Sep 20, 2019 at 13:57

1 Answer 1

1

Python's eval function accepts a globals argument. So you can do something like this:

function = eval('lambda ' + lambda_expression, lambda_globals)
Sign up to request clarification or add additional context in comments.

1 Comment

This works well and looks like a perfect solution for my task. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.