Scope in Python

Scope is a fundamental concept in Python that determines where variables can be accessed or modified in your code. Understanding scope helps you manage variable visibility and avoid common pitfalls, such as variable shadowing and unintended side effects.

Types of Scope in Python

Python has four main types of scope, often remembered by the acronym LEGB:

  1. Local Scope
  2. Enclosing Scope
  3. Global Scope
  4. Built-in Scope

Best Practices for Managing Scope

  1. Minimize Global Variables: Use global variables sparingly to avoid unintended side effects and make your code more modular and testable. Global variable mainly used to define CONSTANT e.g PI = 3.14
  2. Use Local Variables: Prefer local variables for temporary data within functions. They are easier to manage and reduce the risk of interference.
  3. Clear Naming Conventions: Use clear and descriptive names for variables to avoid conflicts between local, enclosing, and global variables.
  4. Encapsulate Code in Functions: Encapsulate code within functions to create local scopes and reduce the complexity of your codebase.

Local Scope

Local scope refers to variables defined within a function. These variables are only accessible within the function where they are declared.

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

my_function()
print(x)  # This will raise a NameError because x is not accessible outside the function.

				
			

Enclosing Scope

Enclosing scope refers to variables in the local scope of enclosing functions. This is particularly relevant in nested functions.

				
					def outer_function():
    y = 20  # Enclosing variable

    def inner_function():
        print(y)  # Accessible within the nested function

    inner_function()

outer_function()

				
			

Global Scope

Global scope refers to variables defined at the top level of a module or script. These variables are accessible throughout the module.

				
					z = 30  # Global variable

def another_function():
    print(z)  # Accessible within any function in the module

another_function()
print(z)  # Also accessible here

				
			

Built-in Scope

Built-in scope refers to Python’s built-in functions and names. These are always available in any scope.

				
					print(len("Hello, World!"))  # len is a built-in function

				
			

Scope Rules

Python follows the LEGB rule to resolve the scope of a variable:

  • Local: Variables defined within the current function.
  • Enclosing: Variables in the local scope of enclosing functions.
  • Global: Variables defined at the top level of a module.
  • Built-in: Names preassigned in Python.

When you reference a variable, Python searches in the order of Local, Enclosing, Global, and Built-in scopes.

Modifying Variables in Different Scopes

Global Variables

To modify a global variable within a function, use the global keyword.

				
					a = 5  # Global variable

def modify_global():
    global a
    a = 10  # Modify global variable

modify_global()
print(a)  # Outputs: 10

				
			

Nonlocal Variables

To modify an enclosing variable in a nested function, use the nonlocal keyword.

				
					def outer():
    b = 15  # Enclosing variable

    def inner():
        nonlocal b
        b = 20  # Modify enclosing variable

    inner()
    print(b)  # Outputs: 20

outer()

				
			
Search

Table of Contents

You may also like to read