0

I tried to localize a module wide variable to the definition in the module, but I got UnboundLocalError and was confused with the reason raising the error. For example, the following codes are implemented in the module test.py

# implementation 1
a=5
def geta():
    a=a
    return a

Import and run:

>>> import test
>>> test.geta()

Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
    test.geta()
File "test.py", line 3, in geta
    a = a
UnboundLocalError: local variable 'a' referenced before assignment

But the following ways work. First one is to define as default value of the input variable a:

# implementation 2
a=5
def geta(a=a):
    return a # return 5

And the second one is to use different name in the definition:

# implementation 3
a=5
def geta():
    b=a
    return b # return 5

Why I can't localize the variable a using implementation 1 with the same name? Why it raises the error referenced before assignment in implementation 1 but works in implementation 3?

Elkan
  • 546
  • 8
  • 23
  • Possible duplicate of [How to change a variable after it is already defined in Python](https://stackoverflow.com/questions/41369408/how-to-change-a-variable-after-it-is-already-defined-in-python) – ash Apr 22 '18 at 09:29
  • @Josh If the most voted answer of your posted question is true, why **implementation 3** works? – Elkan Apr 22 '18 at 09:47
  • In implementation 3, the variable `a` is a global variable, because you don't assign to it within the function. In implementation 1, `a` is a local variable, because you do assign to it. – ash Apr 22 '18 at 10:17

1 Answers1

0
# implementation 1
a=5
def geta():
    global a
    a=a
    return a

You have to make a global variable

TOSTER
  • 1
  • 2