Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch from global to local scope in python?

value = 4

def test():
    global value
    print(value + 2)

    value = -10
    print(value+5)

test()
print(value)

I know it is not a good idea to shadow variables; however, I am attempting this just so I can understand the concept. In the above code, is there a way to switch back to the local scope so that value = -10 only changes value to -10 within the function?

like image 818
Justin Avatar asked Feb 25 '26 06:02

Justin


1 Answers

value = 4

def test():
    print(globals()['value'] + 2)

    value = -10
    print(value+5)

test()

prints

6
-5

There is no way to "switch" between global value and local value once global value has been declared, but you can let value be a local variable within test and access the global value through the globals() dict.

like image 66
unutbu Avatar answered Feb 26 '26 19:02

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!