Python : Scope

In Python, the scope refers to the visibility and accessibility of variables, functions, and other identifiers within a program. Python follows the LEGB rule to determine the order in which it searches for names in various scopes. Here's an overview of the different scopes in Python:

Local Scope (L):


Local scope refers to the innermost scope, typically within a function or method. Variables defined within a function are local to that function and cannot be accessed outside of it.


def my_function():
    x = 10  # Local variable
    print(x)

my_function()  # Output: 10
print(x)  # Error: NameError: name 'x' is not defined

 

Enclosing Scope (E):


Enclosing scope refers to the scope of the enclosing function, in case of nested functions. Inner functions can access variables defined in the outer function's scope.


def outer_function():
    x = 10
    def inner_function():
        print(x)  # Accessing variable from enclosing scope
    inner_function()

outer_function()  # Output: 10
 

Global Scope (G):


Global scope refers to the top-level scope of the module or script. Variables defined at the top-level of a module are in the global scope and can be accessed from anywhere within the module.


x = 10  # Global variable

def my_function():
    print(x)  # Accessing global variable

my_function()  # Output: 10
 

Built-in Scope (B):


Built-in scope refers to the built-in namespace provided by Python, which contains built-in functions, exceptions, and constants.


print(len([1, 2, 3]))  # Output: 3
print(max(4, 7, 2))    # Output: 7

 

LEGB Rule:


Python follows the LEGB rule to resolve names in nested scopes:

  • Local (L): Names defined within the current function or lambda.
  • Enclosing (E): Names defined in the local scope of any enclosing functions, from inner to outer.
  • Global (G): Names defined at the top-level of a module or declared global inside a function.
  • Built-in (B): Names provided by the built-in namespace.

Modifying Global Variables:


To modify a global variable from within a function, you need to use the `global` keyword to declare the variable as global.


x = 10

def modify_global():
    global x
    x = 20

modify_global()
print(x)  # Output: 20

 

Understanding the scope of variables is crucial for writing correct and maintainable Python code. It helps prevent naming conflicts, improves code readability, and ensures that variables are accessible where needed.