Man: Oh boy.
There's some code on the screen
and it looks terribly confusing.
This is an example of a really convoluted,
complicated function that you would never write,
but it'll be good for exercise purposes.
And we're talking specifically about
this right here called non-local.
It's actually a new keyword in Python 3.
And as you can see, my REPL doesn't even notice it
so it doesn't even highlight it in blue
because it is a new feature.
But I do want to talk to you about it
and let you know what it does.
The non-local keyword is used to refer
to this part, this parent local.
It's a way for us to say,
"Hey, I wanna use a variable that is not a global variable
but is outside of the scope of my function."
So based on that definition,
try and pause the video and see what this function might do.
I'll run it right now and then go through the code.
If I click run,
this is what we get.
So let's talk about this.
We have an outer function
and then we call the outer function.
So the Python interpreter is going to go and say,
"All right, we have an X variable that is local
to the outer function."
And then inside of here we're going to define
an inner function, another function.
And in here, before we even call that, we jump to line nine,
and say, "All right, call inner function."
We come back and we say, "Hey, line five,
I wanna use non-local X."
Hmm, what does that mean?
Well, I wanna use this X variable,
because it's non-local.
That is, I don't wanna create a new X variable.
I wanna jump up the scope to my parent scope,
my parent local, and grab whatever you find in there.
As long as it's not global variable, any parent will do.
I wanna grab that non-local.
So now this X is referring to the outer function here.
So when we say X equals non-local,
we're assigning this new
string and replacing this local.
So that when we print inner X, we get non-local,
but also when we print the outer X,
we've modified this outer scope with the non-local keyword,
so that becomes non-local as well.
If I remove this line and let's comment it out,
and I click run, you see the difference now.
We have the inner non-local, but then the outer
local hasn't been modified because this is a new variable.
Again, I argue that this actually makes your code
more complicated than it needs to be.
So there are special cases where you might want to use this
but if you can, try to make your code predictable where
you can avoid using things like non-local and global.
Mind you, they are there for a reason because they are
useful in some situation.
With that said, keep in mind, make your code predictable,
make your code clean, and I'll see you in the next video.