Home >Backend Development >Python Tutorial >Why Does Python Throw an `UnboundLocalError` in Nested Functions, and How Can It Be Resolved?

Why Does Python Throw an `UnboundLocalError` in Nested Functions, and How Can It Be Resolved?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-23 08:20:22721browse

Why Does Python Throw an `UnboundLocalError` in Nested Functions, and How Can It Be Resolved?

UnboundLocalError: Premature Variable Assignment in Nested Blocks

When working with nested function scopes, as in the provided code, Python can encounter the error message "UnboundLocalError: local variable 'c' referenced before assignment." This error occurs when a variable assigned within a nested block is referenced before it is initialized.

In the example code:

a, b, c = (1, 2, 3)

def test():
    print(a)
    print(b)
    c += 1  # UnboundLocalError here

The code attempts to print the variables a, b, and c within the function test(). While a and b are global variables and can be accessed directly, c exists within the function's local scope. As a result, the assignment c = 1 creates a local variable c that overrides the global variable with the same name.

When the code executes, Python initializes a and b and proceeds to call test(). Within test(), it prints a and b successfully, but attempts to print the local variable c before it has been assigned any value, leading to the error.

To resolve this issue, one must explicitly declare the variable as global within the function using the global keyword before assigning any values. This informs Python to use the global variable instead of creating a local one. The corrected code would be:

a, b, c = (1, 2, 3)

def test():
    global c  # Declare 'c' as global
    print(a)
    print(b)
    c += 1

Alternatively, in Python 3, one can use the nonlocal keyword, which refers to the nearest enclosing function scope that has a variable with the same name. This allows one to modify the non-global variable declared in an outer function. The updated code using nonlocal would be:

a, b, c = (1, 2, 3)

def test():
    nonlocal c
    print(a)
    print(b)
    c += 1

The above is the detailed content of Why Does Python Throw an `UnboundLocalError` in Nested Functions, and How Can It Be Resolved?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn