简体   繁体   中英

(Python) I have a string that represents an existing global variable's name, and would like to pass this to a function

x=1

def hi(y):
    exec("global " + y) 
    exec(y + "+=1")

hi("x")
print(x)

I'd like the globally defined x to be incremented by 1, but the output I get is still 1. How can I correct this?

You can access globals by a special keyword, wait for it: globals :)

def hi(var):
    globals()[var] += 1
  • Avoid exec like the plague (till you know what problems it introduces or in 5 years, which ever is later)

  • single letter variable names is a no-no for future readability sake. (it might just be for a demo but I'm saying...)

  • check out this link for scoping rules (with good examples for globals in further posts)

Hope the person passing in 'x' doesn't change it to a invalid variable name like hi(12345) .

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