In the previous article, “An Introduction to Dynamic Execution of Python Code,” we discussed how to execute code dynamically using the exec and eval functions, and how to limit their namespaces so that dynamic code does not “pollute” the environment.

Sometimes, though, we do want dynamic code to generate some local or global definition — such as a variable name — that the original code or later dynamic code can continue to use. A direct definition like the following does not work:

def f():
    a = 1
    exec("a = 3")
    print(a)

The result of this printing will be 1, which means that the change to a in exec is discarded. But you can use the locals parameter to fetch the changes:

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

So this is going to be 3.

The sample code for this article is taken from an article on Stack OverflowQuestion and answer