Home > Software design >  Why does the exec() function work differently inside and outside of a function?
Why does the exec() function work differently inside and outside of a function?

Time:12-06

My question regards the following code examples: Example 1 works fine, while example 2 fails.

# example 1
string_one = 'greeting_one = "hello"'
exec(string_one)

print(greeting_one)
# example 2
def example_function():
    
    string_two = 'greeting_two = "hi"'
    exec(string_two)
    
    print(greeting_two)

example_function()

Example 1 creates the variables in the global scope and example 2 should create the variables in the local scope, otherwise those two should be identical (?). Instead example 2 gives the following error: name 'greeting_two' is not defined. Why is exec() not working as indented in example 2?

CodePudding user response:

Pass the current local scope to the function and use that as the local dictionary for exec(). This can set a variable in the local scope from a function that calls exec().

# example 2
def example_function(loc):
    string_two = 'greeting_two = "hi"'
    exec(string_two, loc)
    print(greeting_two) 

example_function(locals())

Read more here

  • Related