What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Python Variable Scope Guide & Its 4 Types (with LEGB rule)

  • Mar 17, 2023
  • 6 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Abrar Ahmed
Python Variable Scope Guide & Its 4 Types (with LEGB rule)

Python Scoping is a key component in writing clean and maintainable code. As it controls where and how variables can be used, understanding Python variable scope is very important for beginners. We will also learn about its types and LEGB rule.

What is Variable Scope in Python?

Python Scope relates to a variable's visibility and accessibility based on where they are defined in the program. The region of the code where the variable is defined and where it can be used depends on its scope.

Global and local variable scopes are the two primary variations. When a variable is referred to in Python, the interpreter first looks for it in the current function's or block's local scope, then it looks in any enclosing functions or blocks, and finally, it looks in the global scope. A NameError is generated if the variable is not present in any of these scopes.

It's important to remember that variables declared inside a function by default have local scope. The value of the same variable outside the function is unaffected by changes made to the variables inside the function, so to speak. A global variable can be changed inside a function, but the change also affects variables outside the function.

Here is an example to better understand python variable scope:

# global variable
x = 10

def my_function():
    # local variable
    y = 5
    print("Inside the function, x is:", x)
    print("Inside the function, y is:", y)

# call the function
my_function()

# trying to access y outside of the function will cause an error
# print("Outside the function, y is:", y)

# we can modify the value of x inside the function
def change_x():
    global x
    x = 20
    print("Inside change_x function, x is:", x)

# call the change_x function to modify the value of x
change_x()

# now x has been changed to 20
print("Outside the function, x is:", x)

 

Output:

Inside the function, x is: 10
Inside the function, y is: 5
Inside change_x function, x is: 20
Outside the function, x is: 20

 

What are the 4 Types of Scope in Python?

Now that we have discussed what a variable scope is, we must learn its different types. There are four primary scope types in Python:

  1. Local Scope: These variables are only available within the boundaries of the function or block in which they are specified.
  2. Enclosing Scope: This refers to variables defined in the local scope of an enclosing function that can be accessed by its nested functions.
  3. Global Scope: Variables defined outside any function or block have a global scope, accessible and modifiable by the whole program.
  4. Built-in Scope: The names of all the built-in modules are listed in the built-in scope which is available throughout the program.

What is the LEGB rule in Python?

The LEGB stands for the Local, Enclosing, Global, and Built-in scopes. It is the order in which python searches up the value of a variable. When Python encounters a variable name in a code block, it first searches for the name in the local namespace, then searches for the name in the enclosing namespace, then in the global scope, and finally in the built-in scope.

LEGB Rule of Python Scopes

Python considers a variable as a local variable when it receives a value within a function and generates a new variable with the same name in the local scope. Use the global keyword to specify that a variable is a global variable and should be accessed from the global scope if you wish to edit a global variable from within a function.

The nonlocal keyword in Python additionally enables functions to access and alter variables outside of their immediate scope. When you wish to change a variable in a nested function without changing the variable's value in the global scope, this is helpful.

Conclusion

To avoid problems like mistakenly overwriting global variables, naming conflicts, or making code challenging to comprehend or maintain, developers should be aware of variable scope. We learn here what are the types of scopes in Python and the LEGB rule. Happy Learning :)

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Abrar Ahmed
An ambivert individual with a thirst for knowledge and passion to achieve. Striving to connect Artificial Intelligence in all aspects of life. I am also an avid coder and partake in coding challenges all the time on Leetcode and CodeChef.