Search code examples
pythoneval

How to use eval() function with a list of variables?


I have a list of functions as strings:

["y + x + 3", "x**2 + y**2 - 17"]  # 2 functions in list

I have a list of Sympy Symbol objects (basically variables) whos .name attribute cooresponds to the variables names in the function strings:

[Symbol(x), Symbol(y)]
# list element 0's .name attribute is "x" 

I found that Python have a neat function called eval() which can evaluate strings, for example:

x = 1
eval("x + 3") # Result should be 4

Basically this is what I want to do with my functions strings. However, since this is a dynamic implementation I don't have variables defined on a line above eval() in my program, they are in a list instead. For example, in the example above x is defined as 1, so then the eval() function can use it.

But I have my variables in a list, not defined as a variable in the scope of my function. How could I use the eval() function and utilize my list of variables?


Solution

  • eval takes local variables as third argument(reference), so you can do this:

    from sympy import Symbol
    zs = [Symbol('x'), Symbol('y')]
    eval('x+y', None, dict([z.name, z] for z in zs))
    

    However, maybe you should use parse_expr which is part of SymPy.

    from sympy import Symbol
    from sympy.parsing.sympy_parser import parse_expr
    zs = [Symbol('x'), Symbol('y')]
    parse_expr('x+y', local_dict=dict([z.name, z] for z in zs))