What do we call "stack" in Python? Is it the C stack of CPython? I read that Python stackframes are allocated in a heap. But I thought the goal of a stack was... to stack stackframes. What does the stack do then?
What do we call "stack" in Python? Is it the C stack of CPython? I read that Python stackframes are allocated in a heap. But I thought the goal of a stack was... to stack stackframes. What does the stack do then?
Python's stack frames are allocated on the heap. But they are linked one to another to form a stack. When function a
calls function b
, the b
stack frame points to the a
stack frame as the next frame (technically, a
is the f_back
attribute of the b
frame.)
Having stack frames allocated on the heap is what makes generators possible: when a generator yields a value, rather than discarding its stack frame, it's simply removed from the linked list of current stack frames, and saved off to the side. Then when the generator needs to resume, its stack frame is relinked into the stack, and its execution continues.