1

Given the following code

a = 100
b = 200

snip = '''
c = a+b
'''

exec(snip)
print(c)

how can I pass values into exec, and get values out of exec, without using global scope? In effect, I want to be able to explicitly control the entire scope exec has access to.

Warlax56
  • 1,170
  • 5
  • 30
  • Note, in this case, the global `c` was modified, and you can see the effects of that by just doing `print(c)` again after `exec(snip)` – juanpa.arrivillaga Apr 26 '21 at 15:38
  • What is your question??? The code above works and prints 102 and even adding another `print(c)` after the `exec` also prints 102. So... What is your problem/question? – Tomerikoo Apr 26 '21 at 16:10
  • I updated the question to be a bit more clear – Warlax56 Apr 26 '21 at 17:31

1 Answers1

1

Generally, global scope is used with exec

a = 100
b = 200

snip = '''
c = a+b
'''

exec(snip)
print(c)

However, this can be problematic in some use cases. exec allows you to pass in a dictionary defining the global scope, and receive a dictionary containing the local scope. Here's an example:

snip = '''
c = a+b
'''

input_globals = {'a': 100, 'b': 2}
output_locals = {}

exec(snip, input_globals, output_locals)
print(output_locals)

This results in the following output:

{'c': 102}

this effectively allows one to use exec "functionally", without working on and modifying global scope.

You can read this for more detail.

Warlax56
  • 1,170
  • 5
  • 30