0

I am trying to run the following code

def foo():
    exec('foo_value = 1')
    
def foo2():
    foo()
    print(globals()['foo_value'])

foo2()

But i get the error KeyError: 'foo_value'

Is there a way to be able to use the foo_value inside the foo2 function, while the foo_value is created inside another function via the exec() ?

martineau
  • 112,593
  • 23
  • 157
  • 280
quant
  • 3,328
  • 1
  • 21
  • 49

4 Answers4

2

You can make foo_value a global variable by doing this: exec('global foo_value;foo_value = 1')

Kasper
  • 478
  • 3
  • 13
2

If you want to set a global from inside a function, you need the global keyword. (see here)

def foo():
    global foo_val
    foo_val = 1

That should make it work. (Or exec('global foo_val;foo_val=1') inside an exec call)

b9s
  • 467
  • 4
  • 9
2

Yes. When you run the exec function, the code runs in a local scope. In order to make the code accessible to globals simply you can set your global scope in exec code like:

def foo():
    exec('foo_value = 1', globals())
    
def foo2():
    foo()
    print(globals()['foo_value'])

foo2() #output: 1
PaxPrz
  • 1,493
  • 1
  • 9
  • 21
  • Was not aware of the extra parameters of `exec`, good to know! I think I like that more. – b9s Jul 20 '20 at 12:01
1

There is also a function called eval(), it is very similar to exec(), but you could get the returned value of eval()

def foo():
    global foo_val
    fool_val = eval("1")

Although both of them could convert string to code, I strongly don't recommend you using them, because they are unsafe.

Kevin Mayo
  • 1,019
  • 5
  • 18