pythonevalglobal

using eval() inside function with input of function as part of string


I have this code:

def system(into):
    global sys
    x = into
    sis = [eval(i) for i in sys]
    return sis

if __name__ == "__main__":
    sys = ['x[0]+x[1]','2*x[0]-3*x[1]']

I would like to be able to evaluate this system of equation when I execute the system() function with the input into. But I am getting this error: NameError: name 'x' is not defined.

How could I solve this?


Solution

  • You can explicitly pass the list of x values in eval function.Also,Do not use sys for naming variable,sys is in-built python module.Well it does not cause an issue untill or unless you explicitly import that package but this is not a good practice.

    Below is corrected code.

    def system(into):
        global sys
        x = into
        sis = [eval(i, {'x': x}) for i in sys] ## pass explicitly 
        return sis
    
    if __name__ == "__main__":
         sys = ['x[0]+x[1]', '2*x[0]-3*x[1]']