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?