JavaEar 专注于收集分享传播有价值的技术资料

UnboundLocalError:赋值前引用的局部变量'cur' (UnboundLocalError: local variable 'cur' referenced before assignment)

The following code throws the UnboundLocalError:

def fetch_results(conn, sql, **bind_params):
    """
    Immediately fetches the SQL results into memory
    Trades memory for the ability to immediately execute another query
    """
    global _log_func
    try:
        cur = conn.cursor()
        if _log_func:
            _log_func(cur, sql, bind_params)

        cur.execute(sql, bind_params)
        return cur.fetchall()
    finally:
        cur.close()

The error:

line 75, in fetch_results
    cur.close()
UnboundLocalError: local variable 'cur' referenced before assignment

I am not sure why. Could anybody point me to the right direction?

1个回答

    最佳答案

  1. 英文原文

    If conn.cursor() throws an exception, cur will never be assigned, thus the code in the finally block will be referencing cur before assignment.

    Try removing that try block and seeing what happens, its likely that conn.cursor() is throwing some kind of exception you'll need to sort out.


    中文翻译

    如果conn.cursor()抛出异常,则永远不会分配cur,因此finally块中的代码将在赋值之前引用cur。

    尝试删除该try块并查看发生的情况,conn.cursor()可能会抛出您需要解决的某种异常。

    If conn.cursor() throws an exception, cur will never be assigned, thus the code in the finally block will be referencing cur before assignment.

    Try removing that try block and seeing what happens, its likely that conn.cursor() is throwing some kind of exception you'll need to sort out.

    如果conn.cursor()抛出异常,则永远不会分配cur,因此finally块中的代码将在赋值之前引用cur。

    尝试删除该try块并查看发生的情况,conn.cursor()可能会抛出您需要解决的某种异常。