A variable can be modified inside a nested function without being passed as an argument â if Pythonâs scope resolution rules allow it through global or nonlocal.
Can I use both global and nonlocal in the same function?
Why do I get UnboundLocalError when I didnât use global or nonlocal?
Does nonlocal work with nested classes or only functions?
Python resolves names using the LEGB rule : Local â Enclosing â Global â Built-in. This governs read operations: when you reference x, Python checks these scopes in order. At function definition time, the compiler scans all assignments. If any statement assigns to a name (e.g., x = 1, x += 1), that name is classified as local to the function unless declared otherwise with global or nonlocal. This means assignment changes the scope interpretation of a nameâeven if the assignment comes after a read.






