python 3 lambda的参数绑定似乎已中断

2024-10-01 02:20:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在CentOS 7环境中使用Python 3.6.10。我试图创建一个基于结构化规范执行的命令列表。把这看作是一个lambda的列表似乎是很自然的,也是很有吸引力的。我通过遍历规范来构建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虽然有限,但应该创建一个闭包——它在生命中的全部目的是在创建它时捕获它的状态和参数,以便以后在计算lambda时可以使用它们。这就是它被称为“闭包”的原因,因为它在创建时关闭了其参数的值

我误解了什么


Tags: lambdashowwithonelabelthreefourfive
3条回答

这是另一种选择

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)

正如您所说,它创建闭包,闭包使用的是lambdaString的上限范围中的声明变量,但诀窍是所有lambda都使用相同的ref来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: ')

你有一些其他的评论和答案来解释发生了什么,还有你的 “有趣”的问题是它迫使读者困惑的感觉 代码和各种绑定问题

但是,如果我在审查期间从同事那里看到您的代码,我会要求 重写–不是因为我马上就知道有bug,而是因为它 需要对绑定是否来自周围环境进行过多的从头计算 (和不断变化的)作用域将完全按照所希望的那样运行

相反,在你的项目中坚持更严格的纪律,从而减轻压力 读者的认知负荷(大部分时间是)。具体来说,移动 函数创建到一个真正隔离的范围,并传递所有不同的 该函数创建者的输入。这种方法是可靠的,因为它要么 第一次尝试就要努力,否则就会完全失败(如果你忽略了通过所有的测试) 函数创建者所需的参数)

一种方法是:

# 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')

相关问题 更多 >