exec() not working inside function python3.x

I would like to mention that many “standard” answers, previously suggested in this topic, do not work inside a function. For example, consider the following code snippet:

def test():
    exec( 'a = 3', globals(), locals() )
    print(a)
test()

Everything seems fine. However, this code gives an error in Python 3:

NameError: name 'a' is not defined

I tried some methods using the compile function suggested in other forums, but they still do not work for me (at least with the options I have seen mentioned).

According to my research, this the closest code that I have seen working:

def test():
    lcls = locals()
    exec( 'a = 3', globals(), lcls )
    a = lcls["a"]
    print(f'a is {a}')
test()

It successfully prints:

a is 3

I think this is an important topic overall. Sometimes when you work with symbolic algebra libraries, like Sympy, defining variables though the exec function can be very convenient for Scientific Computing.

I hope somebody knows a good answer to the problem.


EDIT:

Nowadays, I rarely use exec anymore. I have realized that a better/shorter solution to the OP question is to simply define local variables using the eval function. The code of the OP could have been written as:

def abc(xyz):
    for i in fn_lst:
        temp = eval(i + '(xyz)')
        print (temp)
abc('avdfbafadnf')
# problem solved :)

Since the variable name temp was already hard-coded into the function, using eval doesn’t change the generality of the solution. If the name of the variable isn’t known beforehand, eval can also be used as follows:

def advanced_eval(expr):
    var_names  = expr.split('=')[0].replace(' ','')
    rhs_values = eval('='.join(expr.split('=')[1:]))
    return var_names, rhs_values

If you define name,value = advanced_eval('a=3+3'), the code will effectively output that name="a" and value = 6.

Leave a Comment