0

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 other words, instead of declaring a, b, and c in global scope, how can I pass a and b into the snippet like a function, and get the result c

Warlax56
  • 1,170
  • 5
  • 30
  • Note: the first time I posted this, I was unaware of a few things, and the question therefore was rendered unclear. The question was then closed. I think this is valuable info, so I revised the question and re-posted it as per stack-overflow guidelines – Warlax56 Apr 26 '21 at 23:24
  • Note 2: I created minimal reproducible code, and created a more clear question to be answered – Warlax56 Apr 26 '21 at 23:26
  • An exact duplicate of https://stackoverflow.com/questions/67269570/pass-variables-into-and-out-of-exec –  Apr 27 '21 at 01:09
  • yep, that was the one I was referencing. Except it was closed because it was unclear (despite edits). This question includes those edits, and also some slight modifications. Strictly speaking it's not an "exact" duplicate, and is nothing like when the question was first asked. – Warlax56 Apr 27 '21 at 04:58

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 via passing by assignment. 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