Is this an efficient and secure way to dynamically generate a function in python?

Viewed 57

So what I'm doing is dynamically generating a function that returns the output of a mathematical equation f(x,y) = z like so:

def compile(self) -> callable[[tuple(float)], float]:
        # user input is something like: xsin(y) + 1 = xcos(y)
        # input is tokenised and syntax is analysed
        # tokens converted to 'eval-able' python code
        # this gives: axes[0]*np.sin(axes[1])+1-axes[0]*np.cos(axes[1])
        # this is stored in evalString

        def func(axes: tuple(float)) -> float:
            v = type(self).variables  # user-defined variables
            f = type(self).functions  # user-defined functions
            return eval(evalString)

        return func

Is there a better way to generate a function like this? I have been told to avoid using exec() due to security issues, but have also been told that eval() isn't much better. I believe that most ways of executing potentially malicious code should be ruled out within the compilation stages, but I am aware that this may not be true and will require further testing.

I am also wondering if using eval() is the best/most efficient way to approach to this or if I should do/use something else?

Many thanks!

0 Answers
Related