0
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?

Lakshay Sharma
  • 827
  • 1
  • 7
  • 19

2 Answers2

2

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

def hi(var):
    globals()[var] += 1
bosnjak
  • 8,424
  • 2
  • 21
  • 47
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).

Community
  • 1
  • 1
Back2Basics
  • 7,406
  • 2
  • 32
  • 45