Stepping Through inner_returned()
So now this is going to be the final call to the
inner() function object that you returned from the
outer() function call. And what happens is, again you will open up a new local scope, just like you did during the other two calls to
And this might be surprising that this is going print
world a second time, because you might wonder, “Okay, so the call to the
outer() function is over, so that scope is closed.” You don’t see the window here anywhere anymore, right?
Like this scope is gone. But because
inner() was defined inside of the
outer() function, it also has access to the variables that were defined inside of the
outer() function, through the so-called nonlocal scope.
So now if you continue execution, you’ll see Python evaluates the
print() call, evaluates
'world', and then it’s ready to print it out, and it shows up on your console. Again, the
print() function returns
None and also,
inner_returned(), because it’s still that function object up here that you’re working with, also returns
And then the third time, the third call to the
inner() function, which I called here
inner_returned() because it’s the returned function object, prints out again the string
world because this was the last value that
message got inside of the definition of the
outer() function and inside of the body of the
inner() function keeps a knowledge of what that variable is through the nonlocal scope of that function. This was a lot to step through, and I hope it made it a little easier by just giving those functions and variables easier-to-understand names and also by using Thonny and seeing the different scopes pop up as separate windows.
That’s about it for this code snippet, but in the next lesson, we’re going to dig a little deeper and figure out where does this variable get stored in Python, like how come does this
inner() function object still has access to this nonlocal variable and where does it live?
Become a Member to join the conversation.