0

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?

martineau
  • 112,593
  • 23
  • 157
  • 280
Mariusmarten
  • 89
  • 1
  • 12
  • 1
    The [docs](https://docs.python.org/3/library/functions.html#exec) warned you about this: "Note: The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted." – user2357112 Dec 05 '21 at 13:54
  • Thank you for the response. I now made greeting_two a global variable first, but the error remained. Is there a way to obtain the same behaviour as for example 1 in example 2? – Mariusmarten Dec 05 '21 at 14:05

1 Answers1

0

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

aprasanth
  • 1,019
  • 7
  • 20