LEGB Rule in Python
Local Scope
: Variables defined within a function are said to have local scope. That means they can only be accessed within that function.Enclosing Scope
: In Python, functions can be defined within other functions. If a variable is not defined in the inner function (local scope) it will be looked for in the enclosing function.Global Scope
: If a variable is not found in the local or enclosing scopes, Python will look for it in the global scope. These are variables defined outside all function definitions.Built-in Scope
: If a variable isn’t found in any other scope, Python will look for it in the built-in scope. These are predefined variables in Python like print(), id(), etc.
Examples:
Local Scope:
def local_example():
local_var = 'I am local'
print(local_var)
local_example() # prints: I am local
Enclosing Scope:
def outer_func():
enclosing_var = 'I am enclosing'
def inner_func():
print(enclosing_var)
inner_func() # prints: I am enclosing
outer_func()
Global Scope:
global_var = 'I am global'
def global_example():
print(global_var)
global_example() # prints: I am global
Built-in Scope:
def built_in_example():
print(len([1, 2, 3])) # len is a built-in function
built_in_example() # prints: 3