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).

Asked By: Woody1193

||

Answers:

Assignments to variables create a new variable in the local scope, unless the nonlocal keyword is used (Python 3 only):

https://www.python.org/dev/peps/pep-3104/

Answered By: Amber
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.