Issue
I am trying to better understanding scoping in python. I have the following toy example:
a = 1
print "in global: " + str(a)
def g():
a += 1
print "in g(): " + str(a)
def f():
a += 1
print "in f(): " + str(a)
g()
f()
I expected this to run and print out 1
then 2
then 2
again. However, instead I get en error:
UnboundLocalError: local variable 'a' referenced before assignment
I would have thought both g()
and f()
would pull a
from the global scope. Incorrect?
UPDATED:
Thanks for the answers but what isn't clear is this: if I would like to just read the global variable a
and assign it to a local variable that I create, also named a
is that possible?
The reason I am doing this is I'm trying to figure out if g()
inherits the scope of f()
when it is called or the global scope where it is defined?
Solution
You are trying to change a
in outer scope of functions, a
is not in the scope of current functions, that's why you are getting such an error, because your functions know nothing about a
. If you want to change a
from within functions you need to use `global':
a = 1
print "in global: " + str(a)
def g():
global a
a += 1
print "in g(): " + str(a)
def f():
global a
a += 1
print "in f(): " + str(a)
g()
to print out the global a
use it this way:
def f():
print a
new_a = a
print new_a
There is a good example about global
here
And if you want to use local variable a
with value from global a
use globals
:
def g():
a = globals()['a']
a += 1
print "in g(): " + str(a)
Answered By - midori
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.