Reputation: 4525
Try this out:
A = 1
B = 2
C = A + B
def main():
global C
print A
The output of main()
is 1
.
Why is this? Why should main
get to know about the other global variables used to evaluate C
?
Upvotes: 1
Views: 938
Reputation: 76955
Global variables are always available to all local scopes in Python, including functions. In this case, within main()
A
, B
, and C
are all in scope.
The global
keyword doesn't do what it seems you think it does; rather, it permits a local scope to manipulate a global function (it makes global variables "writable", so to speak). Consider these examples:
c = 4
print c
def foo():
c = 3
print c
foo()
print c
Here, the output will be
4
3
4
Now, consider this:
c = 4
print c
def foo():
global c
c = 3
print c
foo()
print c
In this case, the output will be
4
3
3
In the first case, c = 3
merely shadows c
until its scope is up (i.e. when the function definition ends). In the second case, we're actually referring to a reference to a global c
after we write global c
, so changing the value of c
will lead to a permanent change.
Upvotes: 8
Reputation: 226231
Functions can read variables in enclosing scopes. The global declaration is used to writing variables (to indiciate that they should be written to the global dictionary rather than the local dictionary).
Upvotes: 4