Variable Scope

Python SELF EN
Level 6 , Lesson 4
Available

10.1 Local Variables in Functions

In Python, a variable is accessible (you can use it) from the moment it's created until the end of its scope — most often that's the function where it's declared. If a variable is declared outside all functions, it’s called global.

In Python, variable scopes define the context in which variables can be used. Scopes help avoid name conflicts and manage data access. The main types of scopes in Python include:

Local Scope: Variables created inside a function exist in the local scope of that function and are accessible only within it.

Enclosed Function Scope: If a function is defined inside another function, its variables are accessible only within that enclosed function.

Global Scope: Variables defined at the script or module level are considered global, and accessible from any part of the code in the same module.

Built-in Scope: This is a special scope that includes all Python built-in objects and functions available by default (like print() and len()).

LEGB Rule

To resolve variables, Python uses the LEGB rule, which determines the order in which the interpreter searches for variables:

  • L (Local) — First, look in the local scope.
  • E (Enclosed) — Then in the scopes of all enclosed functions, from nearest to outermost.
  • G (Global) — Next, in the global scope.
  • B (Built-in) — Finally, in the built-in scope.

Usage Examples


x = "global"  # Global variable

def outer():
    y = "outer local"  # Local variable of outer function
    def inner():
        z = "inner local"  # Local variable of inner function
        print(x)  # Prints "global"
        print(y)  # Prints "outer local"
        print(z)  # Prints "inner local"
    inner()

outer()

The variable z is only accessible inside the inner() function.

The variable y is accessible inside the outer() function and in all functions declared within it.

The variable x is accessible everywhere in the current file (module).

10.2 Accessing Global Variables: global x

An interesting feature of Python is that variables from enclosing scopes (the scope enclosing the current one) can only be read.

If you try to write to an outer variable, a local variable with the same name will be created, and access to the outer variable will be lost.

Example:


x = 10

def change_global():
    print(x)  # This will cause an error because x will be considered a local variable after assignment
    x = 20  # This creates a local variable x
    print(x)  # Prints 20 (refers to the local variable x)
        
change_global()
print(x)  # Prints 10

This example doesn't work and will raise an UnboundLocalError because the Python interpreter first sees the assignment x = 20 and considers x a local variable. However, when the interpreter gets to the line print(x), it doesn't find a local variable x because it hasn't been defined yet.

This is done for safety, so local variables don't accidentally change globals.

The global Keyword

If you need to deliberately change the value of a global variable inside a function, you can use the global keyword. This keyword allows you to explicitly indicate that the change should occur in the global variable, not the local one.

To change a global variable's value inside a function, you need to declare that variable at the beginning of the function using global. This gives the function write access to the variable:


x = 10

def change_global():
    global x  # Declare x as a global variable
    print(x)  # Prints 10 (refers to the global variable x)
    x = 20  # Assigns a new value to the global variable x
    print(x)  # Prints 20 (refers to the global variable x)

change_global()
print(x)  # Prints 20

Using the global keyword helps avoid errors and correctly manage global variables.

Global variables can make a program less predictable and harder to understand because their values can be changed anywhere in the program. This is especially critical if the program is large and developed by a team of programmers.

Although sometimes using global variables is unavoidable, it's better to minimize their usage. Instead of global variables, consider using function parameters, return values, and classes to store state.

Using global variables can lead to unexpected side effects, make debugging and testing the code more difficult, and reduce its reusability. Therefore, it’s recommended to use global variables with caution and only when absolutely necessary.

10.3 Accessing Non-local Variables: nonlocal

Besides global and local variables, Python has variables from intermediate scopes. For example, when a function is nested within another function. To work with such variables, the nonlocal keyword is used.

The nonlocal keyword lets you work with variables in nested functions, changing their values in the nearest enclosing scope, excluding global variables.

The nonlocal keyword helps avoid creating a new local variable in a nested function when you need to change a variable defined in an outer function. Without using nonlocal, changes will only affect the local variable of the inner function, not the variable in the outer function.

Example:


def outer():
    count = 0

    def inner():
        nonlocal count
        count += 1
        return count

    return inner

counter = outer()
print(counter())  # Prints 1

Here’s a more practical example using nonlocal to create a counter:


def create_counter():
    count = 0
    
    def increment():
        nonlocal count
        count += 1
        return count
    
    return increment

counter = create_counter()
print(counter())  # Prints 1
print(counter())  # Prints 2
print(counter())  # Prints 3

This example shows how nonlocal can be used in real scenarios to create a function that maintains its state between calls.

2
Task
Python SELF EN, level 6, lesson 4
Locked
Using a Global Variable
Using a Global Variable
2
Task
Python SELF EN, level 6, lesson 4
Locked
Using a nonlocal variable
Using a nonlocal variable
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION