Open In App

Scope Resolution in Python | LEGB Rule

Last Updated : 13 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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
Scope Resolution in Python

 

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

Python | Scope resolution when a function is called or defined
Python resolves the scope of the parameters of a function in two ways: When the function is definedWhen the function is called When the function is defined Consider this sample program which has a function adder(a, b) which adds an element a to the list b and returns the list b. The default value of b is [1, 8, 11]. Code : C/C++ Code def adder(a, b
3 min read
Python | Pandas TimedeltaIndex.resolution
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.resolution attribute return a string representing the lowest resolution that we have for the given TimedeltaIndex
2 min read
Method resolution order in Python Inheritance
Method Resolution Order : Method Resolution Order(MRO) it denotes the way a programming language resolves a method or attribute. Python supports classes inheriting from other classes. The class being inherited is called the Parent or Superclass, while the class that inherits is called the Child or Subclass. In python, method resolution order define
5 min read
Finding the Size Resolution of Image in Python
Let us see how to find the resolution of an image in Python. We will be solving this problem with two different libraries which are present in Python: PILOpenCV In our examples we will be using the following image: The resolution of the above image is 600x135. Using PIL We will be using a library named Pillow to find the size(resolution) of the ima
2 min read
Change image resolution using Pillow in Python
Prerequisites: Python pillow PIL is the Python Imaging Library which provides the python interpreter with an in-depth file format support, an efficient internal representation, and fairly powerful image processing capabilities. Changing the resolution of an image simply means reducing or increasing the number of pixels in an image, without changing
2 min read
How to change video resolution in OpenCV in Python
In this article, we will describe how you can capture each frame from the video and also resize them according to your needs. What we will exactly do is take the video as input from the user and capture it frame by frame. Moreover, we run the video in the loop and save the image frames with certain names after resizing those frames. Stepwise Implem
3 min read
How To Fix "Typeerror: Cannot Create A Consistent Method Resolution Order (Mro)" In Python
When working with Python, it is usual to encounter mistakes. One such issue, "TypeError: Cannot create a consistent method resolution order (MRO)," might be very aggravating. This issue usually occurs when there is a dispute in the inheritance structure of classes. In this article, we will explore the causes of this error and provide effective solu
3 min read
PyQt5 QCalendarWidget - Getting Horizontal Resolution
In this article we will see how we can get the horizontal resolution of the QCalendarWidget. In order to do this we use logicalDpiX method, it returns the horizontal resolution of the device in dots per inch, which is used when computing font sizes. For X11, this is usually the same as could be computed from widthMM(). In order to do this we will u
2 min read
PyQt5 QCalendarWidget - Getting Vertical Resolution
In this article we will see how we can get the vertical resolution of the QCalendarWidget. In order to do this we use logicalDpiY method, it returns the vertical resolution of the device in dots per inch, which is used when computing font sizes. For X11, this is usually the same as could be computed from heightMM(). In order to do this we will use
2 min read
Pafy - Getting Resolution of Stream
In this article we will see how we can get the resolution of the given youtube video stream in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. Resolution is the quality of the video stream, the most popular standard resolutions are
2 min read
Article Tags :
Practice Tags :