python 3 lambda 的参数绑定似乎已损坏

Argument binding of python 3 lambda appears to be broken

我在 CentOS 7 环境中使用 Python 3.6.10。我正在尝试根据结构化规范创建要执行的命令列表。将其视为 lambda 列表似乎很自然且符合 pythonic。我通过遍历规范来构建 lambda 列表。令我惊讶的是,当我执行结果时,我发现每个 lambda 都是相同的,因为它没有在创建 lambda 时捕获其参数。我认为这是一个错误。

下面是说明该行为的示例代码:

specification = {
    'labelOne': ['labelOne.one', 'labelOne.two', 'labelOne.three', 'labelOne.four', 'labelOne.five'],
    'labelTwo': ['labelTwo.one', 'labelTwo.two', 'labelTwo.three', 'labelTwo.four', 'labelTwo.five'],
    'labelThree': ['labelThree.one', 'labelThree.two', 'labelThree.three', 'labelThree.four', 'labelThree.five'],
    'labelFour': ['labelFour.one', 'labelFour.two', 'labelFour.three', 'labelFour.four', 'labelFour.five'],
    'labelFive': ['labelFive.one', 'labelFive.two', 'labelFive.three', 'labelFive.four', 'labelFive.five'],
    }

lambdas = []
for label, labelStrings in specification.items():
    for labelString in labelStrings:
        lambdaString = f"""Label: \"{label}\" with labelString: \"{labelString}\""""
        oneArgLambda = lambda someArg: print(someArg, lambdaString)
        lambdas.append(oneArgLambda)

for each in lambdas:
    each('Show: ')

我希望看到这个:

Show:  Label: "labelOne" with labelString: "labelOne.one"
Show:  Label: "labelOne" with labelString: "labelOne.two"
Show:  Label: "labelOne" with labelString: "labelOne.three"
Show:  Label: "labelOne" with labelString: "labelOne.four"
Show:  Label: "labelOne" with labelString: "labelOne.five"
Show:  Label: "labelTwo" with labelString: "labelTwo.one"
Show:  Label: "labelTwo" with labelString: "labelTwo.two"
Show:  Label: "labelTwo" with labelString: "labelTwo.three"
Show:  Label: "labelTwo" with labelString: "labelTwo.four"
Show:  Label: "labelTwo" with labelString: "labelTwo.five"
Show:  Label: "labelThree" with labelString: "labelThree.one"
Show:  Label: "labelThree" with labelString: "labelThree.two"
Show:  Label: "labelThree" with labelString: "labelThree.three"
Show:  Label: "labelThree" with labelString: "labelThree.four"
Show:  Label: "labelThree" with labelString: "labelThree.five"
Show:  Label: "labelFour" with labelString: "labelFour.one"
Show:  Label: "labelFour" with labelString: "labelFour.two"
Show:  Label: "labelFour" with labelString: "labelFour.three"
Show:  Label: "labelFour" with labelString: "labelFour.four"
Show:  Label: "labelFour" with labelString: "labelFour.five"
Show:  Label: "labelFive" with labelString: "labelFive.one"
Show:  Label: "labelFive" with labelString: "labelFive.two"
Show:  Label: "labelFive" with labelString: "labelFive.three"
Show:  Label: "labelFive" with labelString: "labelFive.four"
Show:  Label: "labelFive" with labelString: "labelFive.five"

相反,我看到了这个:

Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"
Show:  Label: "labelFive" with labelString: "labelFive.five"

lambda 的参数绑定是在执行 lambda 时发生的,而不是在创建 lambda 时发生的。这至少是出乎意料的,我认为可以说是错误的。

我认为 lambda,尽管它是有限的,但应该创建一个 CLOSURE——它在生活中的全部目的是在创建它时捕获其参数的状态,以便以后可以使用它们评估了 lambda。这就是它被称为“闭包”的原因,因为它在创建时关闭了其参数的值。

我误会了什么?

这是备选方案

lambdas = []
for label, labelStrings in specification.items():
    for labelString in labelStrings:
        lambdaString = f"""Label: \"{label}\" with labelString: \"{labelString}\""""
        oneArgLambda = lambda someArg, lambdaString: print(someArg, lambdaString)
        lambdas.append((oneArgLambda, lambdaString))

for f, lambdaString in lambdas:
    f('Show: ', lambdaString)

正如您所说,它创建了 CLOSURE,并且闭包在 lambdaString 的上层范围内使用了声明的变量,但诀窍在于您的所有 lambda 都使用相同的引用 lambdaString 并且因为每次它记住最后一个时都更改它。例如:

c = ['one', 'two']
res = []

for i in range(2):
    for y in c:
        def la(x):
            print(x, y)
        res.append(la)

for la in res:
    la('Show: ')
# Show:  two
# Show:  two
# Show:  two
# Show:  two

你只需要另一个闭包来防止这种情况

c = ['one', 'two']
res = []

for i in range(2):
    for y in c:
        def closure_y(y):
            def la(x):
                print(x, y)
            return la
            
        res.append(closure_y(y))

for la in res:
    la('Show: ')
# Show:  one
# Show:  two
# Show:  one 
# Show:  two

完整代码可能是

specification = {
    'labelOne': ['labelOne.one', 'labelOne.two', 'labelOne.three', 'labelOne.four', 'labelOne.five'],
    'labelTwo': ['labelTwo.one', 'labelTwo.two', 'labelTwo.three', 'labelTwo.four', 'labelTwo.five'],
    'labelThree': ['labelThree.one', 'labelThree.two', 'labelThree.three', 'labelThree.four', 'labelThree.five'],
    'labelFour': ['labelFour.one', 'labelFour.two', 'labelFour.three', 'labelFour.four', 'labelFour.five'],
    'labelFive': ['labelFive.one', 'labelFive.two', 'labelFive.three', 'labelFive.four', 'labelFive.five'],
    }

lambdas = []
for label, labelStrings in specification.items():
    for labelString in labelStrings:
        lambdaString = f"""Label: \"{label}\" with labelString: \"{labelString}\""""

        def clousure(lambdaString):
            oneArgLambda = lambda someArg: print(someArg, lambdaString)
            return oneArgLambda

        lambdas.append(clousure(lambdaString))

for each in lambdas:
    each('Show: ')

您还有一些其他评论和答案可以解释发生了什么,以及您的 问题是“有趣的”是它迫使 reader 困惑的感觉 代码和各种绑定问题。

但是如果我在审查期间从同事那里看到你的代码,我会要求 重写——不是因为我会立即知道有一个错误,而是因为它 需要太多 head-scratching 是否来自周围的绑定 (和不断变化的)范围将完全按照希望的方式运行。

相反,在你的程序中坚持更严格的纪律,从而减轻 您的 reader(大多数时候 )的认知负荷。具体来说,移动 将函数创建到一个真正隔离的范围,并传递所有不同的 输入 function-creator。这种方法是可靠的,因为它要么 第一次尝试工作或完全失败(如果您忽略通过所有 function-creator).

需要参数

一种方法:

# A function to create another function, with non-surprising argument binding.
# We expect nothing from the surrounding scope. All business can be done locally.
def get_func(label, x):
    return lambda prefix: print(f'''{prefix} => {label}: {x}''')

# Some input data.
specification = {
    label : [label + str(n) for n in range(3)]
    for label in ('A', 'B', 'C')
}

# Use that data to create some functions.
funcs = [
    get_func(label, x)
    for label, xs in specification.items()
    for x in xs
]

# Run 'em.
for f in funcs:
    f('Show')