This code gives the error: UnboundLocalError: local variable \'LINES\' referenced before assignment but LINES is clearly initialized since if I com
You can access global variable from inside foo, but you can't rebind them unless the global keyword is used
So you can use LINES.append(...) or LINES[:] = [] as they are merely modifying the list that LINES references.
When you try to assign to LINES using LINES = [], Python knows it needs to create an entry for LINES in the functions local variables. Since you are trying to use len(LINES) before assigning anything to the local variable, it causes an error
You can inspect foo like this
>>> foo.func_code.co_nlocals
2
>>> foo.func_code.co_varnames
('prob', 'LINES')
If you define foo again without the LINES = [], you'll see that Python no longer marks it as a local variable.
You need to use the global keyword:
def foo():
global LINES
for prob in range(1,3):
print "len(lines) = %d" % len(LINES)
LINES = []
Otherwise, Python will think that LINES is local, and printing out the value before setting it to [] will be an issue
You can get the value of global variable LINES by printing it out, but when you have the statement
LINES = []
which tries to set LINES to a new list, Python interprets it as a local variable
As Desired Login said,
Since you assign to LINES in your example function, python knows not to use the global variable, but you attempt to access this variable before you define it.
This is not the end, you can fix this by using a global keyword, telling python that the LINES in the function is the same as the LINES outside of the function.
Try:
LINES = []
def foo():
global lines
for prob in range(1,3):
print "len(lines) = %d" % len(LINES)
LINES = []
if __name__ == "__main__":
foo()
Python will first look in the function scope for your variable, before it looks in the global (module level) scope. Since you assign to LINES in your example function, python knows not to use the global variable, but you attempt to access this variable before you define it. You should either initialise LINES before the print statement, or leave out the LINES = [] statement.