Silly Techy

Search
Close this search box.

Scope of variables in python

What are Scopes in General ?

Python scopes or scopes in general is a region in the program where a defined variable exists, and beyond this, the program cannot access the variable.

Python Built-IN Scope

Objects like print True False None etc., exist in this scope. These python objects are easily accessible across modules and projects. An example would be print, in which when you open any new python shell or anywhere in different parts of your program, the object is always defined.

Python Global/Module Scope

The global scope in python is essentially the module scope. The global coverage spans a single file only.
As an example, we have a python script my_module.py given below.

				
					# my_module.py

a = 30
				
			

The a is referring to the value 30 . Python is able to access this variable value as 30 throughout this python script my_module.py. This is what is python module or global scope is which is respectively available in the script.

Python Local Scope

During the definition of a function, the assignment operator creates a variable. These variables exist inside this function namespace. When the function is called, then only variables are created. So we can say, A function call leads to variable creation. This existence of the variable value inside the function and this particular region of scope is the pythons local scope.

Python Non Local Scope

Python Non local scope

Suppose we have two functions one inside of the other. As, given below.

				
					def Outter_func():
    
    
        def Inner_func():
    
            pass
    
        Inner_func()
    
        pass    
				
			

Here both the outer and inner functions have access to both the Global and Built-In scopes also their respective local scopes. Here the inner function also has access to the enclosing scope of the outer function. This scope is neither local nor global in respective to inner_function. This scope is called nonlocal scope in python.

How Python check each scope ?

Python will first check for the current local scope. If Python cannot find the variables, it searches in the module/global scope. then it searches in the built-in scope. If still, the Python cannot identify the variable In the three scopes, Python raises variable not defined error.

Using GLOBAL keyword

We can explicitly tell Python that a variable must be scoped in the global scope using the global keyword.
We can change the variable in the global scope inside a functions local scope using this global keyword.

Consider the below example.

				
					a = 10

def func1():
    global a 
    a = 55

func1()

print(a)
				
			

Output:

				
					55
				
			

Using the term “global“, we were able to tell Python that the value of “a” is to be global, so the assignment of a to 55 will change the global value of a.

Share

Facebook
Twitter
Pinterest
LinkedIn

Follow us on

Related Posts

You may also like

On Key

Related Posts