Python: Variable from higher scope "referenced before assignment"
Question:
Suppose I have a method foo:
def foo(string):
def bar1():
if '1' in string:
string = string[2:]
else:
bar2()
def bar2():
if ('2' in string):
string.insert(5, '1')
else:
string.insert(5, '2')
bar1()
Unfortunately, this returns an error stating that local variable string
was referenced before assignment. I thought that string would be inherited from foo
‘s scope. Was I wrong? Note that the variable string
is actually a list (sorry for the confusion).
Answers:
Assignments to variables create a new variable in the local scope, unless the nonlocal
keyword is used (Python 3 only):
Suppose I have a method foo:
def foo(string):
def bar1():
if '1' in string:
string = string[2:]
else:
bar2()
def bar2():
if ('2' in string):
string.insert(5, '1')
else:
string.insert(5, '2')
bar1()
Unfortunately, this returns an error stating that local variable string
was referenced before assignment. I thought that string would be inherited from foo
‘s scope. Was I wrong? Note that the variable string
is actually a list (sorry for the confusion).
Assignments to variables create a new variable in the local scope, unless the nonlocal
keyword is used (Python 3 only):