How to make Python exec work with locals?

Sometimes, we want to make Python exec work with locals.

In this article, we’ll look at how to make Python exec work with locals.

How to make Python exec work with locals?

To make Python exec work with locals, we’ve to convert them to globals.

For instance, we write

def foo():
    ldict = {}
    exec("a=3", globals(), ldict)
    a = ldict['a']
    print(a)

to call exec with the code we want to run, globals(), and ldict.

We call globals to turn a into a global variable.

And then we put the variable result into ldict.

Next, we get the value of variable a from ldict with

a = ldict['a']

Conclusion

To make Python exec work with locals, we’ve to convert them to globals.