Just confused about global value in Python, here are two piece of code
#gl.py
import cli
a = 1
print "gl 1: %d %d" % (id(a), a)
def reset():
global a
a = 7
print "reset 1: %d %d" % (id(a), a)
if __name__ == '__main__':
cli.handler(reset)
print "gl 2: %d %d" % (id(a), a)
the cli code
#cli.py
def handler(func):
from gl import a
print "cli 1: %d %d" % (id(a), a)
func()
print "cli 2: %d %d" % (id(a), a)
The result of execution is
$ python gl.py
gl 1: 150847672 1
gl 1: 150847672 1
cli 1: 150847672 1
reset 1: 150847600 7
cli 2: 150847672 1 #Why value doesn't change
gl 2: 150847600 7
Here I don't understand after "function reset()" execution, the result of global value doesn't change in cli.py(cli 2: 150847672 1), but back to gl.py, global value does change!!
You can change the value of a Python global variable by simply assigning it a new value (redeclaring). To delete a variable, use the keyword del .
In Python, global keyword allows you to modify the variable outside of the current scope. It is used to create a global variable and make changes to the variable in a local context.
While in many or most other programming languages variables are treated as global if not declared otherwise, Python deals with variables the other way around. They are local, if not otherwise declared. The driving reason behind this approach is that global variables are generally bad practice and should be avoided.
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function's body, it's assumed to be a local unless explicitly declared as global.
Two concepts are missing here
Refer: http://legacy.python.org/doc/essays/ppt/hp-training/sld036.htm
Refer: http://docs.python.org/release/2.4/ref/global.html
Refer: https://stackoverflow.com/a/3338357/977038
If you need to share Global variables across modules refer How do I share global variables across modules?
Your gl
module is imported twice into two different namespaces
try this:
import sys
print sys.modules['__main__'].a
print sys.modules['gl'].a
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