jdonlucas
jdonlucas

Reputation: 33

Is there an alternative to exec in python?

So I'm making an integrator program with the simpson 1/3 method and I want the user to give me a function and interval of integration, and then return the result. I figure that I can use exec to make dynamic code, so I use it to create the function. This is my code:

from math import *

class CreaFormula:
    def __init__(self,formula):
        self.fun = "def f(x):\n  return %s" % formula


class Integrador:
    def __init__(self,f):
        #integration interval 
        a = 0
        b = 1
        n = 600 
        h = (b-a)/n
        #method
        self.s = f(a) + f(b)
        for i in range(1,n):
            if i%2 == 0:
                self.s = self.s + 2*f(a+i*h)
            else:
                self.s = self.s + 4*f(a+i*h)

        self.s = self.s*(h/3)
        vr = -cos(1) + e
        self.er = abs((vr -self.s) /vr)


formula = input()
MiFo = CreaFormula(formula)
f1 = MiFo.fun
exec(f1)
MyInt = Integrador(f)

a = MyInt.s
b = MyInt.er
print(a)

So basically I want to put everything that is at the end of the code inside a class, so I can call it later by another code, but if I do that it shows an error that f is not defined, because it is created with exec. So is there a way to not use exec but still create a function from user's input?

Thanks in advance

Upvotes: 0

Views: 1237

Answers (1)

Daniel Pryden
Daniel Pryden

Reputation: 60997

If the question is just how to construct a function object that can evaluate a user-supplied expression, you'll probably have an easier time using eval than exec:

def create_function_from_formula(formula):
    def user_function(x):
        return eval(formula, globals(), {'x': x})
    return user_function

Of course, even with eval, if someone provides a malicious formula, it can do anything, up to and including executing any other program included on the computer. So only do this if you trust the person providing the formula to essentially take over your computer. In particular, you should never do this if formula can come from a user who is not physically logged in to your computer already.

Upvotes: 1

Related Questions