Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
929 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...