I have written some code and recently came across the need for 'nonlocal' when writing functions of functions (came across this when dealing with recursion).
For example:
def swapPairs(head):
head = None
def helper(node):
nonlocal head
...
head= nex.next
return helper(node.next)
My question is quite simple, as we call the recursion function helper(node.next) , and loop back up to nonlocal head - does head take the value of None (due to nonlocal head)? Or does it retain head = nex.next, which it was assigned to in the previous recursion call?
So I am trying to understand whether 'nonlocal head' would cause head to always take the value of whatever it was assigned to in the outer function, or is this not the case? And instead it is just a way to initialise head in the inner function so it only STARTS by taking the initial value as defined in the outer function.
The
nonlocalandglobaldeclarations are for lexical scoping – loosely speaking, they only care about the source code layout.Notably, scoping is not at all concerned with the runtime nesting of the code; it does not care whether
helperis called byswapPairs, a sequence ofhelpers, or some unrelated function: The nameheadinsidehelperis completely equivalent to the nameheadinsideswapPairs.That means the
headinsidedef helperwill always refer to theheadinside theswapPairscall that defineddef helper. Once the first call tohelperassignshead = nex.nextthat changes theheadinside theswapPairsand subsequent calls tohelperwill see (and modify) this new value.