A quick study of global, local and nonlocal Python variables
A Python variable is used to store a value (such as a string, an integer, a float, or a bunch of other types), and when the variable is created a space in memory is reserved. There is no need to declare what data type a variable is in Python — you can just create it and assign it. Let’s take a quick look at the three types of variables: global, local, and nonlocal.
A global variable is one that is declared outside of a function and can be accessed inside or outside of that function. For example:
And the result is:
Now, what happens if I try to modify the global variable inside and outside of the function?
The result is:
So, the global variable can be modified while it is outside the function, but not when it is inside the function. For more, check out Eli Bendersky’s blog. As he explains, the UnboundLocalError happens:
…because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope.
The second type of variable is a local variable. This variable is declared inside of a function and is only accessible to that function (while inside of the function). Here’s an example of a local variable called inside and outside of the function:
The result is:
If I try to access the local variable outside the function, there is a NameError. Python tried to use the variable but doesn't see it defined.
Finally, the third type of variable is the keyword nonlocal. A nonlocal variable is used in nested functions where the local variable should not belong to the inner function. Here’s an example:
For a result of:
By using the keyword nonlocal, I was able to access the x=”nonlocal” outside of the inner function. This is a quick and dirty explanation to highlight the differences between the three types of variables.