4

Title says everything I know

def fun():
    global v
    v = 1
    exec("global " + "k")
    exec("k" + " = 1")

fun()

print(v)
# prints 1
print(k)
# NameError: name 'k' is not defined

I expect the algorithm to print 1 both for v and for k but I get an error.

Mario
  • 561
  • 3
  • 18
  • 1
    Could you expand a bit more on the context of this question? It's not clear what your overall goal is and it's very likely there are better ways to achieve it than using global variables and `exec` statements. – Kyle Parsons Jun 24 '19 at 15:28
  • Thank you Eliahu Aaron, this link helped me fix my issue. – Mario Jun 24 '19 at 15:36
  • Kyle Parsons, the question got answered by including globals() as a parameter to the exec function. Thank you for your time – Mario Jun 24 '19 at 15:42

2 Answers2

0

Just add globals() to the exec function call:

def fun():
    global v
    v = 1
    exec("k" + " = 1", globals())

fun()

print(v)
# prints 1
print(k)
# prints 1
Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37
0

If you need to use the exec you can assign the value of k like this

def fun():
     exec("globals()['k'] = " + "1")

fun()

print(k) # output is 1

Xiidref
  • 1,456
  • 8
  • 20