函数内的闭包

Closure within a function

在一个函数的范围内,我想定义并执行一个闭包,它捕获仅​​存在于“外部”函数范围内的变量。

我通过实验发现,如果分配给捕获的变量,默认情况下它不起作用:行 i+=1 在分配时查找本地 i 。然而,——在没有包装“外部”功能的情况下也能工作——在这里不起作用:

def outer():
    i = 1
    n = 10
    def inner():
        global i, n
        i += 1
        return i == n
    while not inner():
        pass
    print("done")
outer()
# NameError: name 'i' is not defined
# (on the line `i += 1`)

我知道我可以将捕获的变量作为参数传递给 inner,但对于我的实际情况,inner 将作为数据传递并在其他地方执行(在 outer 内),所以理想情况下我不想 partial 它:闭包看起来很合适。

有没有一种干净、清晰的方法可以让我在 Python 中完成这项工作?如果有一种方法我可以不用打字就可以完成这项工作,那就加分了global,这总是让我感到不安。

使用 nonlocal 而不是 global

def outer():
    i = 1
    n = 10
    def inner():
        nonlocal i
        i += 1
        return i == n
    while not inner():
        pass
    print("done")
outer()
# done

感谢评论中的Axe319