Based on what I know. When a function is called, a stack frame should be created which tracks all names and bindings within the functions. The screenshot and code are from 《Introduction to Computation and Programming Using Python》offered by MIT 6.0001.
def f(x): def g(): x = 'abc' print('x =', x) def h(): z = x print('z =', z) x = x + 1 print('x =', x) h() g() print('x =', x) return g x = 3 z = f(x) print('x =', x) print('z =', z) z()
The 7 columns are well understood. In the last line of the code, there is a z()
statement. This statement invokes the function returned by f, which is named g within f. Since an invocation happens, why a new stack frame is not created as there is a variable x that actually binds to ‘abc’ in the function returned?
Advertisement
Answer
Yes, calling z()
also involves creation of a new stack frame. I think the image is simply not concerned with this invocation. Apparently, the seven columns only relate to the line z = f(x)
:
column | -------+------------------- 1 | before calling f 2 | inside f, before calling h 3 | inside h 4 | inside f, after returning from h, before calling g 5 | inside g 6 | inside f, after returning from g 7 | after returning from f