1

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()
nathancy
  • 42,661
  • 14
  • 115
  • 137
xshg
  • 13
  • 3

1 Answers1

0

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_
Eric Jin
  • 3,836
  • 4
  • 19
  • 45
  • 1
    Should I regard as "the variable name demo01 is same name as function demo01()'s name demo01"? U use variable=variable, it's same as variable_name=variable_name() ? – xshg May 14 '19 at 01:21
  • `variable = variable()` if you try this when variable is already defined, then `TypeError: type(obj).__name__ is not callable` the first part of `variable = ` overwrites `variable`'s function definition. You need to use different names for them. – Eric Jin May 14 '19 at 10:28