LEGB Rule in Python Programming
3 min read
LEGB stands for Local, Enclosed, Global, and Built-in
Scope. It's used to define the scope and accessibility of a variable within
the code. The LEGB Rule is a type of name procedure for lookup, which emits a order in which the respective language "Python" lookup for names. LEGB Rule is also used to denote namespaces which stores variable names and values.
The Original Concept of "SCOPE" is that How Variables and Names are looked up into your written code and also emits the visibility of variable within the written code.
As discussed earlier, LEGB stands for Local, Enclosed, Global and Built-in Scope.
So, make LEGB divided into 4 Parts - L E G B
- L - Local Scope
- E - Enclosed Scope
- G - Global Scope
- B - Built-in Scope
Let's discuss in depth about the LEGB Rule -
Local Scope:
It refers to a variable defined in function or class.
Variable defined in the local scope is accessible only within the block in
which it is defined or declared.
For Example -
def func():
x = 'local variable'
print(x)
func()
print(x)
Output -
local variable
NameError: name 'x' is not defined
Enclosed Scope:
It refers to the variable declared inside a function
with nested functions. i.e. Functions defined inside the another
function.
Variable declared in the enclosed scope is accessible from both inner and
outer functions.
For Example -
def func1():
x = 'enclosed variable'
def func2():
y = 'local variable'
print(y)
print(x)
func2()
print(x)
func1()
Output -
local variable
enclosed variable
enclosed variable
Global Scope:
It refers to the variable declared outside of the
function or declared using a global keyword. Variable defined in the global
scope can be accessed anywhere as the word "Global" implies. It can be
accessed anywhere; both inside and outside of the function.
For Example -
x = 'global variable'
def func1():
def func2():
print(x)
func2()
print(x)
func1()
Output -
global variable
global variable
Built-in Scope:
It refers to the variable or functions that are
pre-defined in built-in python modules. Built-in variables or functions can
be used anywhere in the program.
For Example - (1)
from math import pi
print(pi)
Output -
3.141592653589793
For Example - (2)
import builtins
s = builtins.sum([1, 2, 3])
print(s)
Output -
6
So, this was the LEGB Rule in Python Programming.
The canonical, "Python is a great first language", elicited, "Python is a great last language!" - Noah Spurrier