Search code examples
pythonfunctionscopeglobal-variableslocal-variables

Why does the exec() function work differently inside and outside of a function?


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?


Solution

  • Pass the current local scope to the function and use that as the local dictionary for 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