Explaining Variable Scope in Python

Content:

Variable scope refers to the region or part of a program where a variable can be accessed. It is a fundamental concept in programming, and it’s important to understand variable scope to ensure your code functions as intended.

This guide will explain the two main scopes present in Python, as well as looking at scoping rules when using nested functions.

Global Scope

When a variable is defined outside of a function or class, it is referred to as having global scope. A globally-scoped variable is accessible from anywhere else in your code, including inside functions. They are useful when you need to perform multiple operations on the same value.

count = 0

def increment():
    global count
    count += 1

print(count)  # 0
increment()
print(count)  # 1

In this example, the variable count is defined outside of the increment() function.

To use this variable inside the function, the global keyword is used. This ensures that when count is incremented, it is using the global count variable. Without the global keyword, a local variable will be created instead.

Local Scope

A variable declared inside a function has local scope. This means the variable is only accessible from within the function they are defined within, and are not accessible from any external functions. A local variable only exists when the containing function is active.

def sum(num1, num2):
    result = num1 + num2
    print(result)

sum(5, 2)      # 7
print(result)  # Error: NameError: name 'result' is not defined

In this example, the variable result is defined inside the sum() function and has local scope. It can only be accessed within the function. The print() call inside the function has access to the variable, and is able to print result.

Trying to print result from outside of the function results in a NameError. This is because result is not in scope.

Local variables are very useful when separating your code. It provides clarity on the variable being operated on, with no external functions able to alter the value.

Nested Functions

Python supports nested functions, where one function is defined inside another. In this case, the nested function has access to its own local variables, the variables of the enclosing function, and any global variables.

def outer():
    x = 4

    def inner():
        y = 2
        print(x + y)

    inner()  # 6

outer()

In this example, the function inner() directly uses the x variable defined in outer(). This is possible as inner() is nested inside outer(), and the scope of the inner function extends to include the enclosing function.

It’s important to note that it is not possible for inner() to change the value of variables defined in outer() (in this example, setting the value of x). The inner function can only read variables defined in an enclosing function.

To give access, the variable must be declared inside the nested function using the nonlocal keyword.

def outer():
    x = 4

    def inner():
        nonlocal x
        x = 6   # Updating the variable in outer()

    inner() 
    print(x)  # 6

outer()

In this example, x is initially set to 4. This variable is made accessible for the nested function to edit using the nonlocal keyword. The value of x is changed to 6, which is the value which is printed.

Conclusion

By grasping the intricacies of variable scope, you’ll be able to write code that is not only efficient but also less prone to bugs caused by naming conflicts or improper variable usage.

Be sure to check out our other Python tutorials to learn more about coding in Python.