You can access or reference global names from any place in your code, but they can be modified or updated from within the global Python scope.
You can access local names only from inside the local Python scope they were created in or from inside a nested function, but can’t access them from the global Python scope or from other local scopes.
Nonlocal names can be accessed from inside nested functions, but they can’t be modified or updated from there.
These are general rules by default in Python, however there are ways to modify this behavior. There are two keywords that allow you to modify the content of global and nonlocal names:
- global
- nonlocal
With a global statement, you can define a list of names that are going to be treated as global names. The statement consists of the global keyword followed by one or more names separated by commas. You can also use multiple global statements with a name (or a list of names). All the names that you list in a global statement will be mapped to the global or module scope in which you define them.
The use of global is considered bad practice in general.
Similar to global names, nonlocal names can be accessed from inner functions, but not assigned or updated. If you want to modify, then you need to use a nonlocal statement. With a nonlocal statement, you can define a list of names that are going to be treated as nonlocal.
The nonlocal statement consists of the nonlocal keyword followed by one or more names separated by commas. These names will refer to the same names in the enclosing Python scope.
You can’t use a nonlocal statement in either the global scope or in a local scope.