Python Scope

In Python, scope refers to the region within the code where a variable is accessible. Python has four types of scopes, organized under the LEGB rule:

1. Local: The innermost scope, which refers to variables defined within a function.
2. Enclosing: Refers to variables in any enclosing functions, especially for nested functions.
3. Global: The module-level scope, accessible throughout the entire script or module.
4. Built-in: The outermost scope, containing Python’s built-in functions and constants.

1. Local Scope

In the local scope, variables defined within a function are only accessible within that function.
def local_scope_example():
    local_var = "I am local!"
    print(local_var)

local_scope_example()

try:
    print(local_var)  # This will raise an error
except NameError as e:
    print(e)

Output:

I am local!
name 'local_var' is not defined
Explanation: The variable `local_var` is only accessible within the `local_scope_example` function. Attempting to access it outside the function results in a `NameError`.

2. Enclosing Scope

An enclosing scope refers to variables in the outer function of a nested (inner) function.
def outer_function():
    enclosing_var = "I am in the enclosing scope"
    
    def inner_function():
        print(enclosing_var)
    
    inner_function()

outer_function()

Output:

I am in the enclosing scope
Explanation: The `enclosing_var` variable in the `outer_function` can be accessed by the `inner_function` because it is in the enclosing scope. However, it cannot be accessed outside the `outer_function`.

3. Global Scope

Global scope refers to variables defined at the top level of a module or script, accessible from any part of the code within that module.
global_var = "I am global!"

def global_scope_example():
    print(global_var)

global_scope_example()
print(global_var)

Output:

I am global!
I am global!
Explanation: The `global_var` variable can be accessed both inside the `global_scope_example` function and outside of it because it has global scope.

4. Built-in Scope

The built-in scope contains functions and constants that Python provides by default, such as `len`, `str`, and `print`.
# Using the built-in `len` function from the built-in scope
my_list = [1, 2, 3]
print(len(my_list))

Output:

3
Explanation: The `len` function is available in Python’s built-in scope, so you can use it directly without defining it.

Scope Modifiers: `global` and `nonlocal`

In some cases, you may want to modify variables outside the local scope. Python provides `global` and `nonlocal` keywords for this purpose.

Using `global`

The `global` keyword allows you to modify a global variable inside a function.
counter = 0

def increase_counter():
    global counter
    counter += 1

increase_counter()
print(counter)

Output:

1
Explanation: By using `global counter`, we tell Python to use the global `counter` variable instead of creating a local variable with the same name.

Using `nonlocal`

The `nonlocal` keyword allows you to modify an enclosing scope variable within a nested function.
def outer_function():
    count = 0
    
    def inner_function():
        nonlocal count
        count += 1
        print(count)
    
    inner_function()
    print("Count in outer:", count)

outer_function()

Output:

1
Count in outer: 1
Explanation: The `nonlocal count` statement tells Python that `count` refers to the `count` variable in the `outer_function`. Therefore, when we increment it in the `inner_function`, it also updates in the `outer_function`.

These examples demonstrate how Python scope works with variables, following the LEGB rule to determine accessibility in different parts of the code.

Previous: Python Builtin Functions | Next: Python *args and **kwargs

<
>