Overview - Nonlocal keyword
What is it?
The nonlocal keyword in Python lets you work with variables inside nested functions by referring to variables in the nearest enclosing scope that is not global. It allows a function inside another function to modify a variable defined in the outer function. Without nonlocal, inner functions can only read but not change those outer variables. This keyword helps manage variable scope clearly and safely in nested functions.
Why it matters
Without the nonlocal keyword, you cannot change variables in an outer function from inside an inner function, which limits how you write nested functions that share state. This makes it harder to write clean, organized code that uses closures or nested helpers. Nonlocal solves this by giving a clear way to update outer variables, making your code more flexible and easier to understand. Without it, you might resort to confusing workarounds or global variables, which can cause bugs and messy code.
Where it fits
Before learning nonlocal, you should understand how variable scope works in Python, especially local and global scopes. You should also know about nested functions and closures. After mastering nonlocal, you can explore advanced function concepts like decorators, generators, and context managers that often use nested functions and scope manipulation.