Unbound Local Error

蓝咒 提交于 2021-02-05 09:46:54

问题


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.


回答1:


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.




回答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.



来源:https://stackoverflow.com/questions/15094719/unbound-local-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!