我在Python中见过并使用过嵌套函数,它们与闭包的定义相匹配。那么为什么它们被称为“嵌套函数”而不是“闭包”呢?

嵌套函数不是闭包,因为它们不被外部使用吗?

更新:我正在阅读关于闭包的文章,它让我想到了关于Python的这个概念。我搜索了下面评论中有人提到的文章,但我不能完全理解文章中的解释,所以我才问这个问题。


当前回答

《计算机程序的结构和解释》(SICP)的读者:闭包有两种不相关的含义(CS VS Math),后一种含义见维基百科(Wikipedia):

在20世纪80年代,Sussman和Abelson还将闭包一词用于另一个不相关的含义:将数据添加到数据结构中以同时能够添加嵌套数据结构的操作符的属性。该术语的这种用法来自数学用法,而不是先前在计算机科学中的用法。作者认为这种术语上的重叠是“不幸的”。

https://en.wikipedia.org/wiki/Closure_ (computer_programming) # History_and_etymology

第二个(数学)含义也在Python的SICP中使用,参见例如元组的讨论

我们能够将元组用作其他元组的元素,这为我们的编程语言提供了一种新的组合方式。我们把元组以这种方式嵌套的能力称为元组数据类型的闭包属性。通常,如果组合结果本身可以使用相同的方法组合,则组合数据值的方法满足闭包性质。

2.3 Python中的| SICP序列

其他回答

Python 2没有闭包——它有类似闭包的变通方法。

已经给出的答案中有很多例子——将变量复制到内部函数,在内部函数上修改对象,等等。

在Python 3中,支持更加显式和简洁:

def closure():
    count = 0
    def inner():
        nonlocal count
        count += 1
        print(count)
    return inner

用法:

start = closure()
another = closure() # another instance, with a different stack

start() # prints 1
start() # prints 2

another() # print 1

start() # prints 3

nonlocal关键字将内部函数绑定到显式提到的外部变量,实际上将其封闭起来。因此更明确的是一个“闭包”。

def nested1(num1): 
    print "nested1 has",num1
    def nested2(num2):
        print "nested2 has",num2,"and it can reach to",num1
        return num1+num2    #num1 referenced for reading here
    return nested2

给:

In [17]: my_func=nested1(8)
nested1 has 8

In [21]: my_func(5)
nested2 has 5 and it can reach to 8
Out[21]: 13

这是一个关于闭包是什么以及如何使用它的例子。

我遇到了这样一种情况,需要一个单独但持久的名称空间。 我使用课堂。否则我不会。 隔离但持久的名称是闭包。

>>> class f2:
...     def __init__(self):
...         self.a = 0
...     def __call__(self, arg):
...         self.a += arg
...         return(self.a)
...
>>> f=f2()
>>> f(2)
2
>>> f(2)
4
>>> f(4)
8
>>> f(8)
16

# **OR**
>>> f=f2() # **re-initialize**
>>> f(f(f(f(2)))) # **nested**
16

# handy in list comprehensions to accumulate values
>>> [f(i) for f in [f2()] for i in [2,2,4,8]][-1] 
16

这里提供了一种通过代码对象识别函数是否是闭包的方法。

正如在其他回答中已经提到的,并不是每个嵌套函数都是闭包。给定一个复合函数(表示整个动作),它的中间状态可以是闭包或嵌套函数。 闭包是一种由其(非空的)封闭范围(自由变量空间)“参数化”的函数。注意,复合函数可以由这两种类型组成。

(Python的)内部类型代码 对象表示编译后的函数体。它的属性co_cellvars和co_freevars可用于“查看”函数的闭包/作用域。 正如文件中提到的

Co_freevars:自由变量名的元组(通过函数的闭包引用) Co_cellvars:单元格变量名的元组(由包含作用域引用)。

一旦函数被读取,通过递归调用返回一个局部函数,它带有自己的__closure__(因此是cell_contents)和一个来自它的clousre和作用域的自由变量列表。

让我们介绍一些支持函数

# the "lookarounds"
def free_vars_from_closure_of(f):
    print(f.__name__, 'free vars from its closure',  f.__code__.co_cellvars)

def free_vars_in_scopes_of(f):
    print(f.__name__, 'free vars in its scope    ', f.__code__.co_freevars)

# read cells values
def cell_content(f):
    if f.__closure__ is not None:
        if len(f.__closure__) == 1: # otherwise problem with join
            c = f.__closure__[0].cell_contents
        else:
            c = ','.join(str(c.cell_contents) for c in f.__closure__)
    else:
        c = None

    print(f'cells of {f.__name__}: {c}')

这里有一个例子,来自另一个用更系统的方式重写的答案

def f1(x1):
    def f2(x2):
        a = 'free' # <- better choose different identifier to avoid confusion
        def f3(x3):
            return '%s %s %s %s' %  (x1, x2, a, x3)
        return f3
    return f2

# partial functions
p1 = f1('I')
p2 = p1('am')

# lookaround
for p in (f1, p1, p2):
    free_vars_in_scopes_of(p)
    free_vars_from_closure_of(p)
    cell_content(p)

输出

f1 free vars in its scope     ()         # <- because it's the most outer function
f1 free vars from its closure ('x1',)
cells of f1: None
f2 free vars in its scope     ('x1',)
f2 free vars from its closure ('a', 'x2')
cells of f2: I
f3 free vars in its scope     ('a', 'x1', 'x2')
f3 free vars from its closure ()        # <- because it's the most inner function
cells of f3: free, I, am

对应的lambda:

def g1(x1):
    return lambda x2, a='free': lambda x3: '%s %s %s %s' %  (x1, x2, a, x3)

从自由变量/范围的角度来看是等价的。唯一微小的区别是code对象的某些属性的一些值: Co_varnames, co_consts, co_code, co_lnotab, co_stacksize…当然还有__name__属性。


一个混合的例子,闭包和不立即:

# example: counter
def h1():             # <- not a closure
    c = 0
    def h2(c=c):      # <- not a closure
        def h3(x):    # <- closure
            def h4(): # <- closure
                nonlocal c
                c += 1
                print(c)
            return h4
        return h3
    return h2

# partial functions
p1 = h1()
p2 = p1()
p3 = p2('X')

p1() # do nothing
p2('X') # do nothing
p2('X') # do nothing
p3() # +=1
p3() # +=1
p3() # +=1

# lookaround
for p in (h1, p1, p2, p3):
    free_vars_in_scopes_of(p)
    #free_vars_from_closure_of(p)
    cell_content(p)

输出

1 X
2 X
3 X
h1 free vars in its scope     ()
cells of h1: None
h2 free vars in its scope     ()
cells of h2: None
h3 free vars in its scope     ('c',)
cells of h3: 3
h4 free vars in its scope     ('c', 'x')
cells of h4: 3,X

H1和h2都不是闭包,因为它们在作用域内没有单元格和自由变量。 H3和H3是闭包,共享(在本例中)相同的单元格和c的自由变量。h4有一个带有自己单元格的自由变量x。


最后的考虑:

__closure__属性和__code__。Co_freevars可用于检查自由变量的值和名称(标识符) nonlocal和__code__之间的反类比(在广义上)。Co_cellvars:非局部作用于外部函数__code__。Co_cellvars改为内部函数

《计算机程序的结构和解释》(SICP)的读者:闭包有两种不相关的含义(CS VS Math),后一种含义见维基百科(Wikipedia):

在20世纪80年代,Sussman和Abelson还将闭包一词用于另一个不相关的含义:将数据添加到数据结构中以同时能够添加嵌套数据结构的操作符的属性。该术语的这种用法来自数学用法,而不是先前在计算机科学中的用法。作者认为这种术语上的重叠是“不幸的”。

https://en.wikipedia.org/wiki/Closure_ (computer_programming) # History_and_etymology

第二个(数学)含义也在Python的SICP中使用,参见例如元组的讨论

我们能够将元组用作其他元组的元素,这为我们的编程语言提供了一种新的组合方式。我们把元组以这种方式嵌套的能力称为元组数据类型的闭包属性。通常,如果组合结果本身可以使用相同的方法组合,则组合数据值的方法满足闭包性质。

2.3 Python中的| SICP序列