What is the Difference between global and nonlocal in Python?

Question
It seems like "global" and "nonlocal" would be the same thing. How are these keywords different in Python?

Answer
Variables inside a function are local by default; variables outside of functions are global by default. (This was taken from https://www.programiz.com/python-programming/global-keyword.) This answer/article addresses the "LEGB lexical scoping rule" (taken from page 872 of Learning Python).

The "nonlocal" keyword has two requirements that "global" does not have: 1) "nonlocal" must be enclosed in a function within a function; the keyword "def" is crucial here. 2) the variable that the "nonlocal" keyword operates on must be assigned in an outer function (one subsuming the function where the "nonlocal" keyword is).

The "nonlocal" keyword only operates within the scope of the parent function that subsumes the nested/sub function. The "global" keyword will affect the variable at the module level (not inside of a function), but the "nonlocal" keyword will not affect variables outside of any function. "Modules are probably best understood as simply packages of names…" page 694 of Learning Python. In Python "…files morph into namespaces" (page 695 of Learning Python). A source code file with Python statements and Python syntax is a module. One Python program can use other .py files with an "import" command. Outside of any function's definition, you are said to be at the "module level" (but not when you are inside a function).

To clarify "[t]his means that the [nonlocal] variable can be neither in the local nor the global scope." (This was taken from a medium.com article.)

"Python's name-resolution scheme is sometimes called the LEGB rule, after the scope of names: … When you use an unqualified name inside a function, Python searches up to four scopes--the local (L) scope, then the local scopes of any enclosing (E) defs and lambdas, then the global (G) scope, and then the built-in (B) scope--and stops at the first place the name is found. If the name is not found during this search, Python reports an error." This was taken from page 488 from Learning Python.

See also these external postings:
https://stackoverflow.com/questions/1261875/python-nonlocal-statement
https://stackoverflow.com/questions/8050502/pythons-nonlocal-depends-on-level-of-hierarchy

Leave a comment

Your email address will not be published. Required fields are marked *