creamidea / Mushroom

To display Node Capture Data and Control it
Other
0 stars 1 forks source link

UnboundLocalError: local variable 'data' referenced before assignment #48

Open creamidea opened 10 years ago

creamidea commented 10 years ago

出现了这种错误,为何呢?

@json_response
@login_required
def ajax_now_by_policy_id(request, policy_id):
    try:
        policy_id = int(policy_id)
    except Exception, e:
        code = -1
        data = str(e)
    else:
        db = DbOperator()
        code = 0
        data = db.get_policy_instance_now(policy_id=policy_id)
    finally:
        return dict(code=code, body=data)

当我在try里面也写上code, data的时候就没有错误了

@json_response
@login_required
def ajax_now_by_policy_id(request, policy_id):
    # print policy_id, "\\\\\\\\\\\\\\\\\\\\\\\\"
    try:
        policy_id = int(policy_id)
        code = None
        data = None
    except Exception, e:
        code = -1
        data = str(e)
    else:
        db = DbOperator()
        code = 0
        data = db.get_policy_instance_now(policy_id=policy_id)
    finally:
        return dict(code=code, body=data)

难道这里的作用域会变化?

creamidea commented 10 years ago

关于这个变量作用域的问题,首先要明确几个问题:

关于第二点,例子如下:

while True:  
    newvar=8  
    print(newvar)  
    break;  

print(newvar)  

这里的newvar为全局变量,while并不能改变作用域。

Reference:

http://blog.csdn.net/lovingprince/article/details/6627555

creamidea commented 10 years ago

经过一番查找资料和分析,终于知道原来是调用这个函数db.get_policy_instance_now(policy_id=policy_id)时,没有做好正确的处理,在异常发生时,没有什么值返回,于是在return dict(code=code, body=data)时,data就是没有定义的变量了,没有定义就被直接使用,于是就报错了。

然后其实简化出来分析就如同下面这个一样:

CONSTANT = 0

def modifyConstant() :
        print CONSTANT
        CONSTANT += 1
        return

if __name__ == '__main__' :
        modifyConstant()
        print CONSTANT

这里会报错

UnboundLocalError: local variable 'CONSTANT' referenced before assignment

为何?我想你们应该都已经知道了。

Reference: 关于 local variable 'has' referenced before assignment 问题