Introduction to Scope in Python
The scope defines the accessibility of the Python object. You must define the scope to access a particular variable in the code, as it cannot be accessed from anywhere in the program. Scope is the specific coding region that defines the visibility of variables. Variables are not visible to the entire code; programmers can restrict their visibility. Scope determines which variables are ‘seen’. The scope defines the set of rules which tell us how and where a variable can be searched. You search the variable either to retrieve or assign a value. The namespace is the unique identification of the variable or the method. Namespace tells the Python interpreter about the name of the object and the location from where it is trying to access it.
The LEGB rule searches the Namespaces for scope resolution. The LEGB stands for :L: Local, E: Enclosed, G: Global, B: Built-in. The sequence of LEGB is important. First, the program searches for the variable in the local scope, then in the enclosed scope, followed by the global scope, and finally in the built-in scope.
Table of Contents
Types of Scope in Python
Following are the top 4 types of scope in Python:
Let’s study how to declare a variable and how to access its scope:
1. Local Scope
The Variables defined in the function are a local scope of the variable. These variables exist within the function body. Let’s understand this concept with the help of an example. In this example 1, we have taken one variable num. Num = 0 is defined outside the function, so it is not a local variable. As per our definition, the variables declared inside the function body are local variables. Here, num=1 is a local variable that is declared and printed inside the function demo. If we run this code, the output is given below.
Example #1
Code:
num=0
def demo():
#print(num)
num=1
print("The Number is:",num)
demo()
Output:
Num is local to the function. When we use the num variable value in the function before declaring it locally, it raises an error.
Refer to Example 2: The first print statement raises a Python error as we try to access it before the assignment.
Example #2
Code:
num=0
def demo():
print(num)
num=1
print("The Number is:",num)
demo()
Output:
2. Global Scope
The Variable which can be read from anywhere in the program is known as a global scope. These variables can be accessed inside and outside the function. When we want to use the same variable in the rest of the program, we declare it as global.
In Example 1, we have declared a variable Str outside the function. The function demo is called, and it prints the value of variable Str. To use a global variable inside a function, there is no need to use the global keyword.
Example #1
Code:
def demo():
print(Str)
# Global
Str = "You are clever"
demo()
Output:
In the Following Example, 2, We tried to change the value of the global variable Str inside the function; that’s why it raised an exception. If we modify or assign a new value to the variable inside the function, then we must write global. To indicate your intention of using a global variable in Python, you use the “global” keyword. If you don’t declare it global, Python considers the variable local when you create or modify it within the function. This first line throws an exception because Python assumes we want assignment as a local variable due to assignment to str inside function demo().
Example #2
Code:
def demo():
print(Str)
Str = "You are smart"
print(Str)
# Global scope
Str = "You are Clever"
demo()
print(Str)
Output:
To change the value of a global variable inside a function, you use the “global” keyword.
Example 3 solves the problem encountered above.
Example #3
Code:
def demo():
print(Str)
Str = "You are smart"
print(Str)
# Global scope
Str = "You are Clever"
demo()
print(Str)
Output:
3. Non-Local or Enclosing Scope
Non-local variable is the variable that is defined in the nested function. It means the variable can be neither in the local scope nor in the global scope. The nonlocal keyword creates a nonlocal variable. In the following code, we created an outer function, and there is a nested function inner(). In the scope of the outer() function, we define the inner() function. Changing the nonlocal variable defined in the inner() function reflects changes in the outer function.
Example #1
Code:
def func_outer():
x = "local"
def func_inner():
nonlocal x
x = "nonlocal"
print("inner:", x)
func_inner()
print("outer:", x)
func_outer()
Output:
If we want to use the outer function’s value and do not want to make any changes, then comment (nonlocal a) line.
Example #2
Code:
def func_outer():
a = "local"
def func_inner():
#nonlocal a
a = "nonlocal"
print("inner:", a)
func_inner()
print("outer:", a)
func_outer()
Output:
4. Built-in Scope
If a variable is not defined in the local, enclosed, or global scope, Python searches for it in the built-in scope. In the following example, we import the pi value from the math module, and since the pi value is not defined in the global, local, or enclosed scopes, Python looks for the pi value in the built-in scope and prints its value. Therefore, it is advisable not to use names that are already present in the built-in context as identifiers.
Example
Code:
# Built-in Scope
from math import pi
# pi = 'Not defined in global pi'
def func_outer():
# pi = 'Not defined in outer pi'
def inner():
# pi = 'not defined in inner pi'
print(pi)
inner()
func_outer()
Output:
Conclusion – Scope in Python
In this article, we learned about the Python variable scope. We learned four types of scope – global scope, local scope, enclosed scope, and built-in scope. We also learned when to use global and nonlocal keywords. I hope you understood this concept.
Recommended Article
This is a guide to Scope in Python. Here, we discuss the definition and 4 types of scope in Python, along with examples. You can also go through our other related articles to learn more –