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
  • 119,623
  • 25
  • 170
  • 301
quant
  • 4,062
  • 5
  • 29
  • 70

4 Answers4

2

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

Kasper
  • 588
  • 3
  • 16
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
  • 517
  • 4
  • 13
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,778
  • 1
  • 13
  • 29
  • 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,089
  • 6
  • 19