Alex Rivera | Logout

Deferred evaluation with lambda in Python

Asked 2012-06-18T16:26:49.690
14

In a loop, I am trying to defer the comparison the two value()s of two Nodes to a later time.

class Node():
    def __init__(self, v):
        self.v = v
    def value(self):
        return self.v

nodes = [Node(0), Node(1), Node(2), Node(3), Node(4), Node(2)]
results = []
for i in [0, 1, 2]:
    j = i + 3
    results.append(lambda: nodes[i].value() == nodes[j].value())

for result in results:
    print result

The results are all True (because i,j==2,5 for all the lambdas). How can I defer the execution of the lambda until it is actually called, but with the correct variable bindings? And the expressions in the lambda are not all necessarily equality... there are a bunch of other more involved expressions.

Thanks for any help!

Edit
Report

1 Answer

5

The idiomatic way is to use a default argument:

[f() for f in [lambda: i for i in range(3)]]
[2, 2, 2]

Change this to:

[f() for f in [lambda i=i: i for i in range(3)]]
[0, 1, 2]
answered 2012-06-18T16:38:06.377

Your Answer