If you return from a function a nested function, the nested function still has access to the variables that are defined in it regardless whether the function is active or inactive. To demonstrate, let’s look at the following example:
def math():
number = 1
def multiply():
nonlocal number
number = number * 2
return number
return multiply
calculate = math()
print(calculate()) # 2
print(calculate()) # 4
print(calculate()) # 8
What happens above is that the multiply()
inner function is returned which has access to the number
variable from the outer function. The math()
function is no longer being run.