π LEGB Rule
The LEGB rule describes the order Python follows when looking for a variable or name.
LEGB stands for:
L β Local
E β Enclosing
G β Global
B β Built-inPython searches for a name in this order:
Local β Enclosing β Global β Built-in
1οΈβ£ Local
A variable created inside a function is local to that function.
def greet():
name = "Tisha"
print(name)
greet()Here, name is a Local variable.
2οΈβ£ Enclosing
An enclosing variable is found in an outer function when there is a nested function.
def outer():
name = "Tisha"
def inner():
print(name)
inner()
outer()Here, name is not inside inner(), so Python looks in the enclosing function outer().
3οΈβ£ Global
A variable created outside all functions is a global variable.
name = "Tisha"
def greet():
print(name)
greet()Python doesn't find name inside greet(), so it looks in the Global scope.
4οΈβ£ Built-in
If Python doesn't find the name in Local, Enclosing, or Global scope, it checks Python's built-in names.
Examples:
print()
len()
type()
sum()These are available because they are built into Python.
π§© Complete Example
name = "Global"
def outer():
name = "Enclosing"
def inner():
name = "Local"
print(name)
inner()
outer() #LocalPython finds name immediately in the Local scope.
If we remove the local variable:
def outer():
name = "Enclosing"
def inner():
print(name)
inner()
outer() #EnclosingPython then searches the Enclosing scope.