First we show how to make a variable set by the string passed to exec(), available outside of the call to exec(). And then we show some examples of how to make a variable available outside of a call to a function that calls exec().
The central concepts include that exec() takes as arguments, the string to be executed and two dictionaries to serve as global and local scope.
For example, we can pass the actual global and local scope, like this:
exec( 'a = 3', globals(), locals() )
print( a )
This will print the following result:
3
However, there is considerable flexibility in what dictionaries we choose to pass to exec(), and this provides a few ways to set a variable in the local scope from a function that calls exec().
For example, we can pass the current local scope to a function and then use that as the local dictionary for exec(), like this:
def demofunction( adict ):
exec( 'a=1.', globals(), adict )
print( 'before calling the function' )
try:
print( a )
except Exception as e:
print( e )
demofunction( locals() )
print( 'after calling the function' )
print( 'a =', a )
This prints:
before calling the function
name 'a' is not defined
after calling the function
a = 1.0
Since the calling scope is global to the scope inside the function, another simple way to set a local variable from inside a function, is to just use globals() as the second argument for exec().
def demofunction( adict ):
exec( 'a=1.', None, globals() )
print( 'before calling the function' )
try:
print( a )
except Exception as e:
print( e )
demofunction( locals() )
print( 'after calling the function' )
print( 'a =', a )
And this again, prints:
before calling the function
name 'a' is not defined
after calling the function
a = 1.0
So, we see that exec() in fact, can create variables in our local scope from inside a function.
Also, you are not limited to globals() and locals(). You can pass it any valid dictionary.
def demofunction( adict ):
exec( 'a=1.', None, adict )
somedict = { 'b': 1 }
print( somedict )
demofunction( somedict )
print( somedict )
Now the output is:
{'b': 1}
{'b': 1, 'a': 1.0}
Note: In the first examples it would have been sufficient to use the local argument alone, i.e. omitting globals(). Both were included here to illustrate the more general case. You can read about "Scope" in Python, in the Python Textbook - Scope
exec
to do something that can be more easily done without it.