Scope, Stack & Garbage Collector

To complete the topic of compilation and to completely understand – Compilation of the python code OR execution of python code OR what happens when python program is executed – We need to check this topic

Scope :-

Local Scope :-

Scope refers to a “part of program” where a collection of identifiers are visible.

Scope of variable

Consider the above program, contain several scopes. The light yellow region is called the Local scope. What is local scope ? The local scope is the scope of function that the Python interpreter is currently executing. Here it will not get the value of k and list1, so it go for below Enclosing Scope

Enclosing Scope :-

If Python interpreter does not find the k within the local scope, it will examine the Enclosing Scope to see if it can get k there. The identifier defined in this enclosing scope include list1. So it gets list1. For K, it looks for next scope Global Scope

Global Scope :-

The scope outside of all functions is called the global scope. In above figure k is defined in global scope

Built-In Scope :-

The last scope in Python is the Built-In scope. The Global scope is limited with in the module. Consider if an identifier is not found within any of the scopes including Global scope within the modules, then Python interpeter will examine the built-in identifier to check if it is defined there.

For a moment, consider the identifier str() If you were to write the following:
z = str(34)

Runtime Stack & Heap :-

Python Run-time stack and heap

As per the above images, Modules and references are stored in Run-time Stack and Values in Heap. Python divided the RAM into tow parts called Run-time stack and the Heap. As you can see, list1 refers to values in Heap and K to 4 in heap. When program gets executed, if there are no references to the values like k=4, then 4 is removed by the Garbage Collector of the python.

At the end of main function, the add function is called, then activation record of add function is pushed onto the stack and print the list1

This step is the operation that is done by python virtual runtime machine

Please click here for complete information on this

One comment

Leave a Reply