0

I keep getting an unbound local error with the following code in python:

xml=[]       
global currentTok
currentTok=0                     

def demand(s):
    if tokenObjects[currentTok+1].category==s:
        currentTok+=1
        return tokenObjects[currentTok]
    else:
        raise Exception("Incorrect type")

def compileExpression():
    xml.append("<expression>")
    xml.append(compileTerm(currentTok))
    print currentTok
    while currentTok<len(tokenObjects) and tokenObjects[currentTok].symbol in op:
        xml.append(tokenObjects[currentTok].printTok())
        currentTok+=1
        print currentTok
        xml.append(compileTerm(currentTok))
    xml.append("</expression>")

def compileTerm():
    string="<term>"
    category=tokenObjects[currentTok].category
    if category=="integerConstant" or category=="stringConstant" or category=="identifier":
        string+=tokenObjects[currentTok].printTok()
        currentTok+=1
    string+="</term>"
    return string

compileExpression()
print xml

The following is the exact error that I get:

UnboundLocalError: local variable 'currentTok' referenced before assignment.

This makes no sense to me as I clearly initialize currentTok as one of the first lines of my code, and I even labeled it as global just to be safe and make sure it was within the scope of all my methods.

Wilduck
  • 13,822
  • 10
  • 58
  • 90
NIH
  • 151
  • 2
  • 2
  • 8
  • Have a look at http://stackoverflow.com/questions/929777/why-does-assigning-to-my-global-variables-not-work-in-python especially the accepted answer. – Ketouem Feb 26 '13 at 16:53

2 Answers2

4

You need to put the line global currentTok into your function, not the main module.

currentTok=0                     

def demand(s):
    global currentTok
    if tokenObjects[currentTok+1].category==s:
        # etc.

The global keyword tells your function that it needs to look for that variable in the global scope.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
2

You need to declare it global inside the function definition, not at the global scope.

Otherwise, the Python interpreter sees it used inside the function, assumes it to be a local variable, and then complains when the first thing that you do is reference it, rather than assign to it.

Ian Clelland
  • 43,011
  • 8
  • 86
  • 87