-2

How to access a local variable with the same name as a global variable after the global keyword?

var = 0
def foo():
    var = 1
    global var
    var += 1

    #now how i do change the scope to the local variable without deleting var
EpycZen
  • 33
  • 8
  • 1
    *Why?* There's a lot wrong with this, but first, why were you trying to have a function use a local and a global with the same name in the first place? – user2357112 Dec 12 '19 at 11:53
  • Does this help? https://stackoverflow.com/questions/10235973/modifying-global-variable-with-same-name-as-local-variable – Andrej Kesely Dec 12 '19 at 11:56

1 Answers1

3

Give the local variable a different name. global applies for the entirety of the function, you can't switch back and forth as you go. The best you could do is cheap hacks to access the global (globals()['var']) while leaving the name local, but don't do this. Use different names.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271