What is the problem of using upper-level function variables in Python nested functions?

Why does the last two of the following three functions get an exception while the first one doesn"t?

def func(lst=[]):
    def inner_func():
        lst.append(10)
        return lst
    return inner_func()


def func2(num=10):
    def inner_func():
        num += 1
        return num
    return inner_func()


def func3(lst=[]):
    def inner_func():
        lst += [10]
        return lst
    return inner_func()


if __name__ == "__main__":
    print("func:", func())

    try:
        print("func2:", func2())
    except UnboundLocalError as e:
        print("func2:", e)

    try:
        print("func3:", func3())
    except UnboundLocalError as e:
        print("func3:", e)

execution result:

func: [10]
func2: local variable "num" referenced before assignment
func3: local variable "lst" referenced before assignment
Mar.12,2021

The variable scope of

python is divided into legb ( find a random blog post, you can learn about it )

in func2 and func3, you assign num and lst, resulting in the local scope of these two variables, and there is no initial value in the local variable (num + = 1 equals num = num + 1), so an error is reported.

clipboard.png

Menu