Possible Duplicate:
Python variable assigned by an outside module is accessible for printing but not for assignment in the target module
Generally thinking about the scoping rules from other languages, I sort of assumed that the scoping rules of Python is similar for global variables, until I hit a problem for variable count in below code:
count=1
def intPermute(fix,var):
if len(var) ==2:
#import pdb
#pdb.set_trace()
print ("%d: %s%c%c" % (count, str(fix),var[0],var[1]))
count+=1
print ("%d: %s%c%c" % (count, str(fix),var[1],var[0]))
count+=1
else:
for i in range(len(var)):
intPermute(fix+var[i],var[:i]+var[i+1:])
def permuteStr(string):
# permute a string for nPn combinations basically n!
if string =="" or len(string) <=0:
return;
if len(string) <2:
print "%d: %s" % (count, str(string))
intPermute("",string)
I got the following error: File "/Users/ns/permute2.py", line 9, in intPermute print ("%d: %s%c%c" % (count, str(fix),var[0],var[1])) UnboundLocalError: local variable 'count' referenced before assignment
Why the python scoping rules defined such that I can't access the global variable count within inner scope (if statements) of function intPermute ? The same variable is accessible in first statement scope level of the function? Why is that? I understand that one can "override" a global scope variable by defining a local variable of the same name in a function, but this doesn't seem to be the case here.
I was able to add the following statement in the beginning of intPermute function to get around this problem: global count
def intPermute(fix,var):
global count
if len(var) ==2:
#import pdb
#pdb.set_trace()
print ("%d: %s%c%c" % (count, str(fix),var[0],var[1]))
count+=1
print ("%d: %s%c%c" % (count, str(fix),var[1],var[0]))
count+=1
else:
for i in range(len(var)):
intPermute(fix+var[i],var[:i]+var[i+1:])
Now, this meaning of global was not apparent to me, I thought global keyword was to "export" a local variable in global scope.
So 2 questions: 1) Why does Python not allow visibility of global variable count in function intPermute's second level scope? Although it's accessible at the first level scope of the function? 2) Why global keyword resolves this issue? Does it always work for resolving 1 level up global variables?
thanks.