0

So I wanted to create a bunch of functions in a loop to connect for an event. The relevant code is pretty much this:

for i in range(10):
    #Create function for current index
    tmp = lambda: self.do_something(i)
    #and connect event to the function
    event.connect(tmp)

Unexpectedly,(at least for me), when called - all functions act as if i = 9. Tested the same code in ipython with just list comprehention and it behaves the same way:

l = [lambda:i for i in range(10)]
list(x() for x in l)

and the output is:

Out[15]: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]

What's the proper way to achieve the goal of creating 10 different functions this way?

Arthur.V
  • 676
  • 1
  • 8
  • 22

1 Answers1

1

Use a default argument:

event.connect(func, lambda i=i: self.do_something(i))

Since default arguments are evaluated at definition, you're set.

zondo
  • 19,901
  • 8
  • 44
  • 83