Search code examples
pythonvariablesruntime-errorexecglobal

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.


Solution

  • 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

    Edit#2: Either declare ostr as a global variable before modifying it, or assign it to another local variable.

    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)
            
    function()
    

    worked

    True