PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 22, 2022

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

 July 22, 2022     exec, global, python, runtime-error, variables     No comments   

Issue

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



Answered By - Anthony1223
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing