Scope Resolution in Python | LEGB Rule
Last Updated :
13 Sep, 2022
Here, we will discuss different concepts such as namespace, scope, and LEGB rule in Python.
What are Namespaces in Python
A python namespace is a container where names are mapped to objects, they are used to avoid confusion in cases where the same names exist in different namespaces. They are created by modules, functions, classes, etc.
What is Scope in Python
A scope defines the hierarchical order in which the namespaces have to be searched in order to obtain the mappings of name-to-object(variables). It is a context in which variables exist and from which they are referenced. It defines the accessibility and the lifetime of a variable. Let us take a simple example as shown below:
Python3
pi = 'outer pi variable'
def print_pi():
pi = 'inner pi variable'
print(pi)
print_pi()
print(pi)
Output:
inner pi variable
outer pi variable
The above program gives different outputs because the same variable name pi resides in different namespaces, one inside the function print_pi and the other in the upper level. When print_pi() gets executed, 'inner pi variable' is printed as that is pi value inside the function namespace. The value 'outer pi variable' is printed when pi is referenced in the outer namespace. From the above example, we can guess that there definitely is a rule which is followed, in order in deciding from which namespace a variable has to be picked.
Scope resolution LEGB rule In Python
In Python, the LEGB rule is used to decide the order in which the namespaces are to be searched for scope resolution. The scopes are listed below in terms of hierarchy(highest to lowest/narrowest to broadest):
- Local(L): Defined inside function/class
- Enclosed(E): Defined inside enclosing functions(Nested function concept)
- Global(G): Defined at the uppermost level
- Built-in(B): Reserved names in Python builtin modules
Local Scope in Python
Local scope refers to variables defined in the current function. Always, a function will first look up a variable name in its local scope. Only if it does not find it there, the outer scopes are checked.
Python3
# Local Scope
pi = 'global pi variable'
def inner():
pi = 'inner pi variable'
print(pi)
inner()
Output:
inner pi variable
On running the above program, the execution of the inner function prints the value of its local(highest priority in LEGB rule) variable pi because it is defined and available in the local scope.
Local and Global Scopes in Python
If a variable is not defined in the local scope, then, it is checked for in the higher scope, in this case, the global scope.
Python3
# Global Scope
pi = 'global pi variable'
def inner():
pi = 'inner pi variable'
print(pi)
inner()
print(pi)
Output:
inner pi variable
global pi variable
Therefore, as expected the program prints out the value in the local scope on the execution of inner(). It is because it is defined inside the function and that is the first place where the variable is looked up. The pi value in global scope is printed on the execution of print(pi) on line 9.
Local, Enclosed, and Global Scopes in Python
For the enclosed scope, we need to define an outer function enclosing the inner function, comment out the local pi variable of the inner function and refer to pi using the nonlocal keyword.
Python3
# Enclosed Scope
pi = 'global pi variable'
def outer():
pi = 'outer pi variable'
def inner():
# pi = 'inner pi variable'
nonlocal pi
print(pi)
inner()
outer()
print(pi)
Output:
outer pi variable
global pi variable
When outer() is executed, inner() and consequently the print functions are executed, which print the value the enclosed pi variable. The statement in line 10 looks for variable in local scope of inner, but does not find it there. Since pi is referred with the nonlocal keyword, it means that pi needs to be accessed from the outer function(i.e the outer scope). To summarize, the pi variable is not found in local scope, so the higher scopes are looked up. It is found in both enclosed and global scopes. But as per the LEGB hierarchy, the enclosed scope variable is considered even though we have one defined in the global scope.
Local, Enclosed, Global, and Built-in Scopes
The final check can be done by importing pi from math module and commenting on the global, enclosed, and local pi variables as shown below:
Python3
# Built-in Scope
from math import pi
# pi = 'global pi variable'
def outer():
# pi = 'outer pi variable'
def inner():
# pi = 'inner pi variable'
print(pi)
inner()
outer()
Output:
3.141592653589793
Since, pi is not defined in either local, enclosed or global scope, the built-in scope is looked up i.e the pi value imported from the math module. Since the program is able to find the value of pi in the outermost scope, the following output is obtained,
Similar Reads
Variable Shadowing in Python In this article, we will understand the concept of variable shadowing in a Python programming language. To understand this concept, we need to be well versed with the scope of a lifetime of variables in python. Local variables:When we define a function, we can create variables that are scoped only t
3 min read
What Is the @ Symbol in Python? Understanding the significance of the "@" symbol in Python is crucial for writing code that's both tidy and efficient, especially when you're dealing with decorators or performing matrix multiplication operations in your programs. In this article, we'll delve into the role of the "@" symbol in Pytho
3 min read
Pass by reference vs value in Python Developers jumping into Python programming from other languages like C++ and Java are often confused by the process of passing arguments in Python. The object-centric data model and its treatment of assignment are the causes of the confusion at the fundamental level.In the article, we will be discus
7 min read
Namespaces and Scope in Python What is namespace:A namespace is a system that has a unique name for each and every object in Python. An object might be a variable or a method. Python itself maintains a namespace in the form of a Python dictionary. Let's go through an example, a directory-file system structure in computers. Needle
4 min read
__name__ (A Special variable) in Python Since there is no main() function in Python, when the command to run a python program is given to the interpreter, the code that is at level 0 indentation is to be executed. However, before doing that, it will define a few special variables. __name__ is one such special variable. If the source file
2 min read
Undefined Variable Nameerror In Python Encountering the "NameError: name 'var' is not defined" is a common experience for Python users. In Python, variable declaration is a straightforward process of assigning a value. This error arises when attempting to access a non-existent variable or one not defined in the program. Surprisingly, it
5 min read
Getting Started With Unit Testing in Python In Python, unit tests are the segments of codes that are written to test other modules and files that we refer to as a unit. Python Unit Testing is a very important part of the software development process that helps us to ensure that the code works properly without any errors. In this article, we w
8 min read
Protected variable in Python Prerequisites: Underscore ( _ ) in Python A Variable is an identifier that we assign to a memory location which is used to hold values in a computer program. Variables are named locations of storage in the program. Based on access specification, variables can be public, protected and private in a cl
2 min read
Python Tokens and Character Sets Python is a general-purpose, high-level programming language. It was designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines of code, and these codes are known as scripts. These scripts contain character sets, tokens, and identifiers.
6 min read
Python Scope of Variables In Python, variables are the containers for storing data values. Unlike other languages like C/C++/JAVA, Python is not âstatically typedâ. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. Python Scope variabl
5 min read