Search code examples
pythonfunctionlocal

How to fix two object same name 'local variable referenced before assignment' Error in Python


I defined one function, and in the function or another function I assign the same-name value by call the same-name function. I get this error

UnboundLocalError: local variable 'demo01' referenced before assignment

The error occurs here

def demo01():
    return 5

def demo02():
    demo01=demo01()

demo02()

UnboundLocalError: local variable 'demo01' referenced before assignment

But these snippets are fine

def demo01():
    return 5

def demo02():
    demo01=demo01()

demo01 = demo01()

def demo01():
    return 5

def demo02():
    demo02=demo01()

demo02()

Solution

  • When there is an existing variable, creating a new one under that name will overwrite the existing variable, for example:

    print = 2 # change the print() function to a variable named 2
    print('string')
    

    will give

    TypeError: 'int' object is not callable
    

    going back to your code:

    demo01 = lambda: 5 # this is more of an advanced keyword, feel free to do it your way
    
    def demo02():
        demo01 = demo01() # "demo01 = [val]" tells python to assign a value to demo01, and you cannot assign a variable to the same variable:
    
    variable = variable
    

    obviously not possible; gives

    NameError: name 'variable' is not defined
    

    when used in a global state and UnboundLocalError when used in a local (class or function).

    Your variable names and other variables, if any, used during assignment MUST NOT BE OR REFERENCE THE VARIABLE YOU ARE CURRENTLY ASSIGNING.

    If you really need to use the same variable:

    variable_ = variable()
    variable = variable_