Search code examples
pythonpython-3.xscopeclosures

Inner function not printing nonlocal variable


I have one outer function and 2 inner functions.

def outer():
    x = 'hello'    
    def inner1():
        def inner2():
            nonlocal x
            x = 'python'        
        inner2()
        print(x)
outer()

Why is the above code not printing the value of x?

As per my understanding, it should print "hello".


Solution

  • Your code calls outer(), which in turn executes only one statement:

    x = 'hello'
    

    As it stands, the code in your question will print nothing.

    If you were to add the line print(x) after the call to outer(), it would indeed print "hello", as you have suggested.

    If you were to instead add the line inner1() to call the function by that name which is defined inside outer(), then inner1() would in turn call inner2() which would in turn cause x = 'python' to execute, and this would change the value of x and (thanks to the nonlocal x line within inner2()) the statement print(x) within inner1() would cause the code to print "python".