简体   繁体   中英

why can't I declare a global variable inside an "exec" string

I am trying to declare and change a global variable in an exec string, like this:

ostr = "didn't work"
nstr = "worked"
def function():
    exec("global ostr; ostr = nstr")
    #global ostr; ostr = nstr
    print(ostr)
    lv='ostr' in globals()
    print(lv)
    ostr='asd'

function()

However, this errors out on the print statement with:

UnboundLocalError: local variable 'ostr' referenced before assignment

But, if I comment out the "exec" line and uncomment line after the exec statement, the code works fine.

How can I fix this error using "exec"? I want to declare variables global and modify those global variables inside an exec string and have those modifications visible in "function" on subsequent lines.

You have to declare that you are using global ostr in the function to be able to print it. This piece of code outputs

def function():
   global ostr
   exec("global ostr; ostr = nstr")
   #global ostr; ostr = nstr
   print(ostr)
   lv='ostr' in globals()
   print(lv)
   ostr='asd'

worked

True

Edit: Just realised the exec actually works with global variables, if you re-run your code and print(ostr) in the global main you will see it was changed.

ostr = "didn't work"
nstr = "worked"
def function():
    #global ostr
    exec("global ostr; ostr = nstr")

function()
print(ostr)

worked

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM