Python Lambdas and Variable Bindings

前端 未结 2 1008
忘了有多久
忘了有多久 2020-11-29 09:50

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 differe

2条回答
  •  囚心锁ツ
    2020-11-29 10:20

    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.

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

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

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

    Another way is to create the lambda inside a function:

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

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

提交回复
热议问题