Layers of Functions

Now that you've got an idea of what functions are and how they work, it's useful to think about them in terms of how they are called and how Python keeps track of these layers of invocations.

When your program calls a function, or a function calls a function, Python creates a list inside of itself that is called the stack or sometimes the call stack. When you invoke a function (or call on, which is why it can be called a call stack), Python will stop for a moment, take note of where it is when the function was called and then stash that information in its internal list. It'll then enter the function and execute it, as you've seen. For example, the following code illustrates how Python keeps track of how it enters and leaves functions:

[{'top_level': 'line 1'}, {'make_omelet': 'line 64'}, {'make food': 'line 120'}]

At the top, Python keeps track starting at line 1. Then, as the function make_omelet is called at line sixty-four, it keeps track of that. Then, from inside of make_omelet, make_food is called. When the make_food function finishes, Python determines that it was on line 64, and it returns to line 64 to continue. The line numbers in the example are made up, but you get the idea.

The list is called a stack because of the way in which a function is entered. You can think of a function as being on the top of a stack until it is exited, when it is taken off, and the stack is shortened by one.

Was this article helpful?

0 0

Post a comment