Skip to main content

Different Python Scopes Explained

The scope of this post is limited to variable and basic info about the variable. What you will not find is the nitty gritty of how to define a variable and what are the valid rules to types of values can it contain etc.If need then there will be an another post specifically for variables in python.

Lets start with what variables are and then we will get into more details.

What is a variable?
A variable is just a holder for something which varies. If I say it in more general terms, the variable is a container which has a characteristic to change over the time.

But for those who are looking for more of a formal definition here we go:
'In computer programming, a variable or scalar is a storage location (identified by a memory address) paired with an associated symbolic name (an identifier), which contains some known or unknown quantity of information referred to as a value.'[1]

When we define variables in python they get linked to a scope(a textual region inside a python program).
Scope here helps in narrowing the area in which the variable can be accessed.

A particular textual region(scope) has its corresponding variable entered as a key value pair in the corresponding namespaces(a python dictionary containing unique entries which helps in restricting unique names of variables or function in the program).

Sorry for the inconvinence.But for more details about this image check reference 2 under the refenreces section.
[2]
Here we have different scope starting from Local -> Enclosing -> Global -> Built in their increasing order of their range of accessibility.

But I am still thinking, why do we need a scope cant we just create the variables in one place and access them according to our needs?

We can actually access the variables without defining the scope(scope gets defined implicitly).
But there is a need to maintain the scopes as we need to limit the area of influence of the variables.Also, one more things needs to be made sure that only a particular variable is active, if two of them have the same names.
By doing this we are making sure that the unique nature of a particular variable in that scope is established when their scope is active.

As of now we know what a variable is, why scope is needed and the types of scopes.

Next, as the context of the scopes is established we can now move towards the LEGB Rule used by interpreter when searching for a variable.

The first scope where the interpreter looks for the variables is the local scope with the least influence circle and then as we move towards global variables the influence circle increases which then ends with the built in keywords.

Example for local variable




Example of Enclosing scope


Example for Global scope


Example of Built in variables

Next,
If you want to know what all variables, function or classes that are there inside the global or local scopes, we have some symbol table which records these things.

We can access the global symbol table or namespaces which contains all the information necessary for the current program to run. These details can be accessed by making a call to the globals() or the locals() function. These function returns a dictionary of key value pair in which the values can be changed. 

The output of the globals function for the given program is as follows:

 
Output:


Same is the case for the local symbol table which will contain all the details about the local function, variables, classes etc.
The symbol table for the local scope can be accessed using locals() function which too return a dictionary and also it too can me augmented with new values

The output of the locals function for the given program is a follows:

Note all the above code was executed on the following online code editor:
https://www.tutorialspoint.com/execute_python_online.php

That's all for this post!!

Thank you for reading this post.

If you have any suggestions regarding the post contents or if you need some more details on any other topic, please post it in the comments section.
Your suggestions are too valuable so they should not be missed.

References:
1.https://en.wikipedia.org/wiki/Variable_(computer_science)
2.https://data-flair.training/blogs/python-variable-scope/
3.https://www.programiz.com/python-programming/methods/built-in/globals
4.https://www.programiz.com/python-programming/methods/built-in/dir
5.https://www.programiz.com/python-programming/methods/built-in/locals
6.https://www.tutorialspoint.com/execute_python_online.php


Comments

Popular posts from this blog

PyMuPDF vs PDFMiner

 As a developer , I was tasked to extract specific data from a PDF. Upon analysing it further, certain patterns were found based on keywords in the document. Since I was using Python language for the task I found 2 tools quite useful which are PyMuPDF and PDFMiner. These tools can then be used to extract the text from a page on which regular expression can be applied to further extract relevant data.     Next, we are going to take a deeper look into these tools, specifically focusing on the pros and cons of each.     PyMuPDF   Docs , PIP package Pros Simple and understandable API Extensive tools to work with text, images, and graphics Available as a PIP package (pip install PyMuPDF) Better support for a range of symbols comparer to PyPDF2   Cons Parsed text is not in sequence Dependency on other package-Fitz Text sequence information lost during extraction     PDFMiner   Docs ,  PIP package ...

Finding difference between 2 files in Python

In this post, we will take a look at how to compare two files using Python.   I was tasked to compare 2 files and then list the differences between them using Python. Initially, I started with filecmp module, but even with the function parameter ‘ shallow’ set to false, the Boolean result was not enough. Sure, it can act as an indicator to take some action, but it will not list the differences.   I was looking for something more visual, something like color coding and not like the git diff output, which is not very user-friendly. But, another Python internal module, difflib helped me to get the job done.   Inside Difflib, HtmlDiff is what I was looking for. The differences were highlighted with 3 different colors and also the line numbers were indicated in a table to locate the differences. The results are quite self-explanatory and it is easier to explain the differences to other people. Code for generating the above difference table: Note: File1...

Adding existing Anaconda environment to Jupyter notebook

In this post we are going to take a look at adding Anaconda environment to Jupyter notebook. Recently, I was working on a CSV file and wanted to work with Pandas package for tabular data manipulation using Python. The problem was even if I install Pandas package, I would have to install other Data Science package as needed. But, the Anaconda environment was already setup on my laptop, which I want to reuse.   Today, we will look into how to reuse the Anaconda environment within the Jupyter Notebook.   There are 4 basic steps to be followed for adding the environment: 1. Create a conda environment Go to Conda command prompt(Run in Admin mode) Run the following command: conda create –-name newenv O/P:   What if there is an existing conda environment? Go to Conda command prompt(No need for Admin mode) Run the following command: conda env list O/P: Since there was only one environment, only one entry was displayed. ‘*’ indicates the cur...