Consider the following example:
def g():
in_g=100
def f1():
nonlocal in_g
in_g = 10
def f2():
nonlocal in_g
print(in_g)
return (f1,f2)
(f1, f2) = g()
f2() #prints 100
f1()
f2() #prints 10
Both the inner functions, f1 and f2, have, in their "closures", access to the variable in_g.
However, after g returns, where is in_g kept in the memory?
I assume that while g is executing, in_g is a variable on the stack frame corresponding to a call to g. Therefore, g, f1 and f2 all access the same memory location (on the stack) when using the variable in_g.
But, as seen in the example, after g returns, f1 and f2 still access the same memory location when referencing in_g. However, now that g returned, that memory location cannot be on the stack anymore.