2
votes

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
On which line is the error? - John Zwinck
The error is at the cur.close() - Istvan

1 Answers

6
votes

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.