Executing stringified python function from python script

Viewed 92

I'd like to use Python's eval in a way similar to that of Javascript. In Javascript, I can eval something like this:

const myfunc = eval('function(arg1, arg2) { ...... }');
myfunc(1, 2);

First of all, I'll start by saying that the functions being run are NOT from userland - only the admins on our team are writing the functions, and it's a core part of our product architecture. I'm aware of the security implications :)

Some things that I have thought of myself include:

  1. During runtime (so the format is preserved), using a library to convert the code into a single-liner. But I don't really want to rely on a third party library for doing this as that introduces potential future security holes.
  2. Temporarily saving the script to a file and importing that file dynamically using importlib. But then I end up with a potentially weird server state if file management commands fail or are used improperly, and I'm paranoid that I'll call the wrong script and execute the wrong code.

I don't really love either of these options. I know that I could make them both work if I had to, but was hoping to get input from people who know Python much better than I do.

1 Answers

I used the 2nd option - its much better than eval.

Files containing entire class and its functions can be written at runtime and executed. Using some scheme where you write a different class name each time and match the class name and function name can ensure you call the correct script when needed.

Related