Sobes.tech
Junior

What are the scope areas in Python?

sobes.tech AI

Answer from AI

In Python, the following scopes exist:

  • Local (L): The innermost scope, belonging to the current function or class. Variables defined inside a function are only accessible within that function.
  • Enclosing (E): The scope of enclosing functions. Variables defined in an outer function are accessible from inner (nested) functions within it.
  • Global (G): The module scope. Variables defined at the top level of a module are accessible anywhere within that module.
  • Built-in (B): The outermost scope, containing Python's built-in functions, types, and constants (e.g., print(), len(), True). These are accessible without explicit import.

Python searches for variables in the scope order LEGB: first in Local, then Enclosing, then Global, and finally Built-in.

# Global scope
global_var = "I am a global variable"

def outer_function():
    # Enclosing scope
    enclosing_var = "I am a variable of the enclosing function"

    def inner_function():
        # Local scope
        local_var = "I am a local variable"
        print(f"Inner function:")
        print(f"  Local: {local_var}") # Access to local variable
        print(f"  Enclosing: {enclosing_var}") # Access to enclosing variable
        print(f"  Global: {global_var}") # Access to global variable
        print(f"  Built-in: {len([1, 2])}") # Access to built-in function

    inner_function()

outer_function()

print(f"\nGlobal scope:")
print(f"  Global: {global_var}") # Access to global variable
# print(enclosing_var) # Error: variable not visible in global scope
# print(local_var) # Error: variable not visible in global scope

The keywords global and nonlocal are used to modify scope behavior when assigning values:

  • global: Allows modifying a variable in the global scope from within a function.
  • nonlocal: Allows modifying a variable in the nearest enclosing (non-global) scope from within a nested function.
global_var_mod = "Initial global value"

def modify_scopes():
    enclosing_var_mod = "Initial enclosing value"

    def inner_modify():
        global global_var_mod # Declare that we want to modify the global variable
        nonlocal enclosing_var_mod # Declare that we want to modify the enclosing variable
        
        global_var_mod = "Modified global value"
        enclosing_var_mod = "Modified enclosing value"
        local_var_mod = "Local value" # This is a new local variable
        print(f"Inside inner_modify:")
        print(f"  Global: {global_var_mod}")
        print(f"  Enclosing: {enclosing_var_mod}")

    inner_modify()
    print(f"Inside modify_scopes (after inner_modify):")
    print(f"  Enclosing: {enclosing_var_mod}") # The modified enclosing value is visible

modify_scopes()
print(f"In global scope (after modify_scopes):")
print(f"  Global: {global_var_mod}") # The modified global value is visible
What are the scope areas in Python? — Python - sobes.tech