What is a stack in Python?
Simplifies a little:
In CPython, when it PyEval_EvalFrameEx
evaluates a Python stack frame code and comes up with a direct function call, it allocates a new Python stack frame, binds it ... and then recursively calls PyEval_EvalFrameEx
on that new frame.
So the C stack is a stack of recursive calls to the interpreter loop.
The Python stack is a stack of Python frame objects, implemented as a simple linked list of heap allocated objects.
They are not completely unrelated to each other, but they are not the same thing.
When you use generators it gets a little more confusing because these Python stack frames can be detached and reloaded in different places when they are resumed. This is why the two stacks are separate. (See Ned's answer, which explains this better than I could.)
source to share
Python stack frames are allocated on the heap. But they are linked together to form a stack. When the function a
calls the function b
, the stack frame b
points to the stack frame a
as the next frame (technically, a
an attribute of the f_back
frame b
.)
Having stack frames allocated on the heap makes generators possible: when a generator gives a value, rather than discarding its stack stack, it is simply removed from the linked list of current stack frames and stored aside. Then, when the generator should resume, its stack stack is redirected onto the stack, and execution continues.
source to share