exec() command in python can't change global variables from inside function

Viewed 334

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.

2 Answers

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

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

Related