How are Python variables scoped?

In Python, variables are scoped based on where they are declared and accessed in the code. The scope of a variable determines where it can be accessed or modified. Python uses the LEGB rule to determine the scope of a variable. The rule defines the search order for variable names as follows:

LEGB Rule

  1. Local (L):
    Variables defined inside a function or a block are considered local. These variables are accessible only within that specific function or block. def my_function(): x = 10 # Local variable print(x) # Accessible only inside this function
  2. Enclosing (E):
    Variables in an enclosing function’s scope (a function containing another function) are considered enclosing variables. These variables are accessible to nested (inner) functions but cannot be modified unless explicitly declared using the nonlocal keyword. def outer_function(): x = 20 # Enclosing variable def inner_function(): print(x) # Accessing the enclosing variable inner_function()
  3. Global (G):
    Variables defined at the top level of a module or script (outside of all functions or classes) are considered global. They are accessible throughout the module. To modify a global variable inside a function, you must declare it with the global keyword. x = 30 # Global variable def my_function(): global x x = 40 # Modify the global variable
  4. Built-in (B):
    Names that are part of Python’s built-in functions or constants, like len, str, or True, are in the built-in scope. These are always available in any Python program. print(len("hello")) # `len` is a built-in function

Scope Modifiers

  1. global:
    Used to indicate that a variable inside a function refers to the global variable. x = 50 def modify_global(): global x x = 60 # Modifies the global variable
  2. nonlocal:
    Used to modify an enclosing (non-global) variable from within a nested function. def outer_function(): x = 70 def inner_function(): nonlocal x x = 80 # Modifies the enclosing variable inner_function() print(x) # Will print 80

Key Points

  • Variables declared inside a function are local to that function unless explicitly marked as global or nonlocal.
  • Python raises a NameError if you try to access a variable outside its scope.
  • Python variables are resolved using the LEGB rule, starting from the innermost (local) scope and moving outward.

My Thought

Your email address will not be published. Required fields are marked *

Our Tool : hike percentage calculator