When I execute a testing script in my company's Python project, I got an error as below:
UnboundLocalError: local variable 'a' referenced before assignment
I wrote some simpler code to reproduce the issue, it has 2 files.
vars.py file:
#!/usr/bin/env python
a = 'aaa'
script.py file:
#!/usr/bin/env python
from vars import *
def myFunc1():
print a
if False:
a = '111'
print a
myFunc1()
Execute the code:
$ python --version
Python 2.7.10
$ python script.py
Traceback (most recent call last):
File "script.py", line 13, in <module>
myFunc1()
File "script.py", line 6, in myFunc1
print a
UnboundLocalError: local variable 'a' referenced before assignment
$
I googled the UnboundLocalError
and found some useful information like:
UnboundLocalError: local variable 'L' referenced before assignment Python
UnboundLocalError in Python
According to the answers in above 2 questions, if I add a global a
after the def myFunc1():
line in script.py file, the error is gone.
The thing I don't understand is removing the if
condition from myFunc1
can also make it work...
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…