The Call Stack

Python keeps track of any running functions using a runtime stack (see Figure 7.8, on the next page). We can think of the stack as a series of records, called frames (see Figure 7.9, on the following page), which pile up on top of each other as functions are called. Only the top frame is active; the rest are paused, waiting until functions above them are finished.

Code outside of any function is executed in a special frame that is at the bottom of the stack; this frame is called <module> because it is executing at the module level.

When a function is called, Python creates a new frame for it and adds the frame to the top of the stack. These frames store information about each function call and the order they were called in. The most recently called function's frame always sits at the top of the stack.

As we will see later in this chapter, each stack frame stores a function's parameters and local variables. It also contains a reference to the next statement Python will execute when the function finishes. This is known as the return address.

Figure 7.8: Runtime stack

Function name




_local1 "local2

Local variables

Figure 7.9: A stack frame

Finally, the frame has space set aside for storing the function's return value, which we will see later in the chapter.

When a function finishes executing, Python then checks the stack to see what it should run next. This information is stored in the return address of the frame at the top of the stack. Once Python knows where to go, it removes the frame.

When your Python program is finished executing, there will be no more frames on the stack.

Was this article helpful?

0 0

Post a comment