Python Lambda 和变量绑定 [英] Python Lambdas and Variable Bindings

查看:79
本文介绍了Python Lambda 和变量绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究用于自动化构建的基本测试框架.下面的这段代码代表了使用不同程序对两台机器之间的通信进行的简单测试.在我实际进行任何测试之前,我想完全定义它们 - 所以下面的这个测试在所有测试都被声明之后才真正运行.这段代码只是一个测试的声明.

I've been working on a basic testing framework for an automated build. The piece of code below represents a simple test of communication between two machines using different programs. Before I actually do any tests, I want to completely define them - so this test below is not actually run until after all the tests have been declared. This piece of code is simply a declaration of a test.

remoteTests = []
for client in clients:
    t = Test(
        name = 'Test ' + str(host) + ' => ' + str(client),
        cmds = [
            host.start(CMD1),
            client.start(CMD2),

            host.wait(5),

            host.stop(CMD1),
            client.stop(CMD2),
        ],
        passIf = lambda : client.returncode(CMD2) == 0
    )
remoteTests.append(t)

无论如何,在测试运行后,它运行'passIf'定义的函数.由于我想为多个客户端运行此测试,因此我正在迭代它们并为每个客户端定义一个测试 - 没什么大不了的.但是,在第一个客户端上运行测试后,'passIf' 对客户端列表中的最后一个进行评估,而不是 lambda 声明时的 'client'.

Anyhow, after the test is run, it runs the function defined by 'passIf'. Since I want to run this test for multiple clients, I'm iterating them and defining a test for each - no big deal. However, after running the test on the first client, the 'passIf' evaluates on the last one in the clients list, not the 'client' at the time of the lambda declaration.

那么我的问题是:python 何时绑定 lambdas 中的变量引用?我想如果使用来自 lambda 外部的变量是不合法的,解释器将不知道我在说什么.相反,它默默地绑定到最后一个客户端"的实例.

My question, then: when does python bind variable references in lambdas? I figured if using a variable from outside the lambda was not legal, the interpretor would have no idea what I was talking about. Instead, it silently bound to the instance of the last 'client'.

另外,有没有办法按照我想要的方式强制分辨率?

Also, is there a way to force the resolution the way I intended it?

推荐答案

client 变量定义在外部作用域中,因此在 lambda 运行时将始终设置为列表中的最后一个客户端.

The client variable is defined in the outer scope, so by the time the lambda is run it will always be set to the last client in the list.

为了得到预期的结果,你可以给 lambda 一个带有默认值的参数:

To get the intended result, you can give the lambda an argument with a default value:

passIf = lambda client=client: client.returncode(CMD2) == 0

由于在定义 lambda 时评估默认值,因此其值将保持正确.

Since the default value is evaluated at the time the lambda is defined, its value will remain correct.

另一种方法是在函数内创建 lambda:

Another way is to create the lambda inside a function:

def createLambda(client):
    return lambda: client.returncode(CMD2) == 0
#...
passIf = createLambda(client)

这里的 lambda 引用了 createLambda 函数中的 client 变量,它具有正确的值.

Here the lambda refers to the client variable in the createLambda function, which has the correct value.

这篇关于Python Lambda 和变量绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆