Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
922 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...