In the following code:
options=["INFO", "WARNING", "DEBUG"] for i in range(len(options)): option=options[i] __cMenu.add_command( label="{}".format(option), command=lambda: self.filter_records(column, option) )
several lambdas are created and saved. These lambdas should capture different values of the local variable option. However, when these lambdas are used, they all behave as though option was set to "DEBUG", the last value it takes on in the loop.
This issue arises due to the evaluation timing of names in function bodies. In the provided code, the names are evaluated when the function is executed. As a result, the lambdas created in the loop all refer to the same value of option at the time of execution, which is "DEBUG".
To circumvent this problem, the following modification can be made:
__cMenu.add_command(label="{}".format(option), command=lambda opt=option: self.filter_records(column, opt))
By introducing option=option as an argument to the lambda function, each lambda captures the correct value of option at the time of creation, rather than relying on the value at the time of execution. This ensures that each lambda operates on the desired value of option.
The above is the detailed content of Why Do My Lambdas in a For Loop Only Use the Last Value?. For more information, please follow other related articles on the PHP Chinese website!