Memory recovery of python closure

A note on closures elsewhere

"the external function finds that its own temporary variable will be used in the internal function in the future. When it ends, when it returns the inner function, it will send the temporary variable of the outer function to the inner function to bind together. So the outer function has been finished, and the temporary variable of the outer function can still be used when calling the inner function."

Q: how does the outer function know which temporary variable is bound to the inner function?
for example, in the following example, f binds a to g after execution and deletes c but g does not execute it. How does f know that g needs a?

import sys

a = 2
c = 25
print(sys.getrefcount(25))
d = 25
print(sys.getrefcount(25))
def f():
    a = 25
    c = 25
    print(sys.getrefcount(25))
    def g():
        print(a)
    return g

l = f()
print(sys.getrefcount(25))
l()
print(sys.getrefcount(25))
"""
-----------------------------
49
50
52
51
25
51
"""
Mar.29,2021

at compile time, the variable is already bound to the inner function. Another 25 is very common in programs, and the change in the number of references may be different from what is expected (the variable calculates the "number of references" at compile time instead of counting at execution time)

Menu