In this post we’ll see what is nonlocal keyword in Python and how to use it.
To understand nonlocal keyword better an understanding of local, global and nonlocal variables is required, as a requisite please go through this post- Local, Nonlocal And Global Variables in Python
Python nonlocal keyword
The nonlocal keyword causes the variable to refer to previously bound variables in the nearest enclosing scope excluding globals. Note that nonlocal keyword is added in Python 3.
Python nonlocal keyword is used with variables in nested functions to bind the variable defined in outer function, by making variable nonlocal it can be accessed in nested function.
Let’s try to understand it with some examples.