Nonlocal Quick Review
Local Variables = Variables that are defined in your current frame
Up until this point, we have only used local variables and variables from parent frames in our functions. However, we were only ever able to change the values of the local variables. What if we could change the values of variables from our parent frames?
Nonlocal Variables = Variables that are not defined in our current frame that we can change the values of
Two important rules
In order to declare a variable nonlocal in you current frame:
It must be defined in a parent frame (or a grandparent, great-grandparent etc. frame, if you will) of your current function that is not the global frame
It cannot share a name with a variable that is local to your current frame
NONLOCAL WITH ENVIRONMENT DIAgrams
When defining a nonlocal variable in an environment diagram, you do not write it in your current frame. I recommend marking it (maybe with a star) in whatever frame it came from, just to remind yourself that it is nonlocal, and so you may be changing its value from the frame that you are in.
Now let’s see an example:
def f(x):
def g(y):
nonlocal x
x = 3
return x + y
g(5)
return x
f(6)
When we make the first call, f(6), we will assign x to 6 and define the g function, which we then call. When we call g, we assign y to 5 and declare x to be nonlocal. Since we have an x in the parent frame of g (since g was defined in the body of f), the x that we are referring to is the x from f. We set x equal to 3 and then return x + y, which is 3 + 5. That ends the call to g. Now, when we return x, since we changed it in our call to g, we return 3 instead of 6. The environment diagram is linked below if you want to check it out.