Last Time We learned that there are two areas of memory in a program.
- Heap The heap is the object warehouse. It is divided into bytes, each of which has a (memory) address. Periodically, the garbage collector comes and deallocates the memory of unsused objects residing on the heap.
- The Stack This area of memory manages function calls. Each time a function is called, a container called a stack frame or activation record is created. This container holds the function's local variables. It knows where its caller left off, and it has a bookmark that marks where the current function is in its execution. When a function returns, any return value is passed back to the caller, its stack frame is destroyed, and the caller resume execution right where it left off. The mechanism of the stack is how Python function scope is implemented.
Further we should remark that the only things stored by variables living on the stack are the memory addresses of objects. Such addresses are no bigger than 8 bytes. Space on the stack is fairly limited.
On the other hand, objects in the heap can be quite large. For instance, you can easily store the contents of War and Peace in the heap.
The Main Routine Actual execution of a python program begins here. All of your python programs should look like this.
##Put all of your imports first. import math . . (other imports) import os ##then define all of your functions def first(x): return x + 1 . . . def last(x,y): return f"x = {x}, y = {y}" ##here is where the main routine starts x = 4 q = 3 print(last(x,q))
When this function executes, the imports are done, then all of the functions get read into memory. These functions are visible during the entire lifetime of the program.
Next the main routine executes. You should think of it as just another function. When the main routine runs out of code, the program's execution terminates and its memory escheats to the operating system, which can use it to run other programs.