Sashank Varma Datla
Sashank Varma Datla

Reputation: 23

global variable doesn't work when I use exec

Whenever I execute my code with following snippet, it works perfectly fine.

def set_globvar_to_one():
    global globvarq
    globvarq = 2

def print_globvar():
    print(globvarq)

set_globvar_to_one()
print_globvar()

But, in my case, I need to execute this snippet using exec command as my code is dynamic. So, I tried following.

def set_globvar_to_one():
    exec(compile("global globvarq","setglobal","exec"))
    exec(compile("globvarq = 2","setglobal","exec"))
def print_globvar():
    eval(compile("print(globvarq)","setglobal","eval")) 

set_globvar_to_one()
print_globvar()

and this code is throwing following error.

Traceback (most recent call last):
    print_globvar()
    eval(compile("print(globvarq)","setglobal","eval"))
  File "setglobal", line 1, in <module>
NameError: name 'globvarq' is not defined

How can I make the variable global from one method and use the same variable in another method?

Upvotes: 1

Views: 176

Answers (1)

Grismar
Grismar

Reputation: 31319

I'm not sure what you're actually trying to achieve, but this does what you expected:

def set_globvar_to_one():
    exec(compile("global globvarq\nglobvarq = 2", "setglobal", "exec"))


def print_globvar():
    eval(compile("print(globvarq)", "setglobal", "eval"))


set_globvar_to_one()
print_globvar()

Upvotes: 1

Related Questions