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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With