4
def foo():
    m = 3
    def bar():
        print(m) # code 1
        m=4 # code 2
    bar()
foo()

UnboundLocalError: local variable 'm' referenced before assignment

Why do I get the UnboundLocalError? I know bar can't change the value of m, but shouldn't barjust be able to get the value of m?

And when I try the code 1/code 2 separately, it all works.

Bharata
  • 13,509
  • 6
  • 36
  • 50

1 Answers1

3

Since the inner function bar has an assignment m=4, m is considered as a local variable, for whole of the function. But at the point you invoke print(m), m is not yet created. So you get the error UnboundLocalError: local variable 'm' referenced before assignment.

In Python 3, you can fix the code by declaring m to be nonlocal in the inner scope. This avoids placing m in the global scope (which is also an option in both Python 2 and 3 using the global keyword in place of nonlocal). The following code works in Python 3:

def foo():
    m = 3
    def bar():
        nonlocal m
        print(m) # code 1
        m=4 # code 2
    bar()
foo()
Attila the Fun
  • 327
  • 2
  • 13
Sunitha
  • 11,777
  • 2
  • 20
  • 23
  • So the compiler look at the whole of the function bar and know there is a local m, but isn't python executed line by line?I guess the process of py->pyc did it( look at the whole of the function bar), Then the machine execute the pyc line by line.(I search the Internet) the Sorry I am a newbie, thanks! – Liu Charles Aug 11 '18 at 12:59