首页 > 解决方案 > variable change in nested func not recognized in other func with variable passed as arg

问题描述

I have the following simplified version of my code:

import time


def inner(condition, callback):
    while condition:
        print('test')
        time.sleep(1)
        callback()


def outer():
    condition = True

    def callback():
        nonlocal condition
        condition = False

    inner(condition, callback)


outer()

Currently, the above code continues to print, even though i change the condition variable to false in the callback function. I want the condition to change to False, and the while loop to exit.

How come the variable change is not detected in the inner func?

标签: python

解决方案


那是因为conditionininner()是一个局部变量,callback()改变了condition的第一行中定义的outer(),但不能改变 的局部变量inner()。因此, 中的条件inner将始终为True。这可以通过以下代码验证

def inner(condition, callback):
    # while condition:
    #     print('test')
    #     time.sleep(1)
    #     callback()
    print('condition in inner before callback(): {}'.format(condition))
    callback()
    print('condition in inner after callback(): {}'.format(condition))




def outer():
    condition = True

    def callback():
        nonlocal condition
        condition = False

    inner(condition, callback)
    print('condition in outer after callback() called in inner: {}'.format(condition))


outer()

一种解决方法是将 更改condition为列表:[True]. List 是python中的可变对象,这意味着改变它的元素不会改变它在内存中的地址,conditionininner()不断更新conditionin outer()

def inner(condition, callback):
    while condition[0]:
        print('test')
        time.sleep(1)
        callback()


def outer():
    condition = [True]

    def callback():
        nonlocal condition
        condition[0] = False

    inner(condition, callback)

outer()

推荐阅读