3

I understand that python stores call stack and references on the stack and the value objects on the heap. But how does closure and especially the non-local variables (the variables defined in outer function and used inside closure) fall in this category?

The description of closure says A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory. Yet we all know it's impossible to access any value if it really vanishes in memory. So does that mean the reference of non-local variables (on the stack) are deallocated yet their value objects (on the heap) are kept and referred by the closure?

Update: I ran the following code and obviously the address of the free variable is never changed, which (probably) means the value objects on heap are not deleted even after the outer function terminates...yet still: if the outer function is removed from memory after it's called, where is the content of inner function stored? and are the reference (i.e. name) of the free variables also unchanged on the stack or the inner function actually has another copy of these names which refers to the true value objects on the heap?

the code I used:

def fn_out(a):
    print("fn_out::a", hex(id(a)))
    def fn_in(b):
        print("fn_in::a", hex(id(a)))
        return a * b
    return fn_in

f = fn_out(3)
# freevars = f.__code__.co_freevars
for i, v in enumerate(f.__closure__):
    c = v.cell_contents
    print("the %ith free variable: at"%i, hex(id(c)), "content:", c)
f(2)

output:

fn_out::a 0x9a3140                                                 
the 0th free variable: at 0x9a3140 content: 3                      
fn_in::a 0x9a3140   
trincot
  • 317,000
  • 35
  • 244
  • 286
Crystina
  • 990
  • 1
  • 5
  • 16
  • This answer should help [Where does Python store the name binding of function closure](https://stackoverflow.com/questions/32221063/where-does-python-store-the-name-binding-of-function-closure) – DarrylG Mar 27 '20 at 20:40
  • @DarrylG Thanks! I went through that question and it's really helpful. Updated the question accordingly. – Crystina Mar 27 '20 at 21:51

0 Answers0