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
2
  • 2
    Does this answer your question? Python nonlocal statement Commented Mar 17, 2020 at 12:57
  • The nonlocal statement causes the listed identifiers(in this case its x) to refer to previously bound variables in the nearest enclosing scope excluding globals Commented Mar 17, 2020 at 12:57

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

That is only because the nonlocal statement is used.
@GoodDeeds Did I imply anything else?
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).
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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.