Stepping Through inner_returned()
In the previous lesson, you stepped through most of this code that we have here on the page, but you stopped shortly before calling
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 now you still have access to the
message variable, as you can see here through the nonlocal scope of the
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.
And because the last value that
message got inside of this function definition was
'world', it still points to that same string.
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 that finishes the execution of your script. So now your output is one time
hello from the first call to the
world from the second call to the
inner() function, which both still happen inside of the
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?
02:38 And you’ll jump a little into an interpreter session and play around with it to figure out how Python handles this internally.
Become a Member to join the conversation.