Python Forum
UnboundLocalError: local variable referenced before assignment - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: UnboundLocalError: local variable referenced before assignment (/thread-23386.html)



UnboundLocalError: local variable referenced before assignment - svr - Dec-27-2019

Hi

Need some help here
Original code
def test1():
    test_list = []
    test_var = 0
    test_string1 = ""

    def test2():
        temp =2
        if temp > test_var:
            test_var = temp
        else:
            test_string = "fail"
        return test_string
    
    res = test2()
    print res

test1()
https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value

I used both global , nonlocal but both throws different error

def test1():
    test_list = []
    test_var = 0
    test_string1 = ""

    def test2():
        nonlocal test_var
        temp =2
        if temp > test_var:
            test_var = temp
        else:
            test_string = "fail"
        return test_string
    
    res = test2()
    print res

test1()
throws this error
nonlocal test_var ^
SyntaxError: invalid syntax


def test1():
    test_list = []
    test_var = 0
    test_string1 = ""

    def test2():
        global test_var
        temp =2
        if temp > test_var:
            test_var = temp
        else:
            test_string = "fail"
        return test_string
    
    res = test2()
    print res

test1()
throws this error ^
NameError: global name 'test_var' is not defined

Any suggestions ? I have gone through top 10 search results , all suggest to use nonlocal or global...


RE: UnboundLocalError: local variable referenced before assignment - perfringo - Dec-27-2019

This is topic with lot of subtlety. Some of the scenarios are discussed in this thread: Namespace and scope difference

I think that this boils down to this:

Quote:You should also understand difference between reference and assignment:

When you reference a variable in an expression, the Python interpreter will traverse the scope to resolve the reference in following order:

- current function’s scope
- any enclosing scopes (like containing functions)
- scope of the module that contains the code (global scope)
- built-in scope (that contains functions like int and abs)

If Python doesn't find defined variable with the referenced name, then a NameError exception is raised.

Assigning a value to a variable works differently. If the variable is already defined in the current scope, then it will just take on the new value. If the variable doesn’t exist in the current scope, then Python treats the assignment as a variable definition. The scope of the newly defined variable is the function that contains the assignment.