1

Isn't it supposed to return 'inner: nonlocal' and 'outer: local'?? Can someone explain what's happening, thanks.

>>>>def outer():
        x = 'local'
        def inner():
            nonlocal x
            x='nonlocal'
            print('inner:',x)
        inner()
        print('outer:',x)

>>>outer()
 inner: nonlocal
 outer: nonlocal
Young
  • 27
  • 2
  • 2
    Does this answer your question? [Python nonlocal statement](https://stackoverflow.com/questions/1261875/python-nonlocal-statement) – GoodDeeds Mar 17 '20 at 12:57
  • The [`nonlocal`](https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement) statement causes the listed identifiers(in this case its `x`) to refer to previously bound variables in the nearest enclosing scope excluding globals – Abdul Niyas P M Mar 17 '20 at 12:57

2 Answers2

1

You are setting x to 'nonlocal' by calling inner(). Thus, x is set to 'nonlocal' no matter where you try to print it from within outer(). Put the print statement before the call to inner() and it will work.

Robey
  • 53
  • 1
  • 8
  • That is only because the `nonlocal` statement is used. – GoodDeeds Mar 17 '20 at 12:59
  • @GoodDeeds Did I imply anything else? – Robey Mar 17 '20 at 15:51
  • Sorry, I misphrased my comment. While your answer is correct, I think the OP is asking why the `x` set in the scope of `inner()` is visible in `outer()`, and this is because of the `nonlocal x` statement in `inner()`. (as addressed by the other answer). – GoodDeeds Mar 17 '20 at 15:58
1

See enter link description here link for information on non-local.

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.

In short, it lets you assign values to a variable in an outer (but non-global) scope.

If you remove the keyword nonlocal and try your program, you will observe:

inner: nonlocal
outer: local

Program:

def outer():
    x = 'local'
    def inner():
        x='nonlocal'
        print('inner:', x)
    inner()
    print('outer:', x)


outer()
abhiarora
  • 9,743
  • 5
  • 32
  • 57