Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python global variable not defined in for loop

This code gives the error: UnboundLocalError: local variable 'LINES' referenced before assignment but LINES is clearly initialized since if I comment out the line below the print statement it throws no errors and prints len(lines) = 0 as expected. Am I not understanding something about python?? Whats going on here?

LINES = []

def foo():
  for prob in range(1,3):
    print "len(lines) = %d" % len(LINES)
    LINES = []

if __name__ == "__main__":
  foo()
like image 351
anthonybell Avatar asked Feb 14 '26 08:02

anthonybell


2 Answers

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.

like image 82
John La Rooy Avatar answered Feb 16 '26 21:02

John La Rooy


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

like image 27
jh314 Avatar answered Feb 16 '26 21:02

jh314



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!