Python create list of function pointers to be called later specifying arguments at creation
Question:
The easiest way to explain the problem is by showing the code:
def foo(stuff):
print(stuff)
fun_list = [lambda :foo(i) for i in range(5)]
for fun in fun_list:
fun()
When the functions are called they all print 4
. I would like them to print the actual value of i
from when they were created, so 0
, 1
, 2
, 3
, and 4
. This is all part of a large multithreaded project, which I need to use this blueprint.
Answers:
You need to pass i as an argument in lambda funcion
fun_list = [lambda x=i: foo(x) for i in range(5)]
The easiest way to explain the problem is by showing the code:
def foo(stuff):
print(stuff)
fun_list = [lambda :foo(i) for i in range(5)]
for fun in fun_list:
fun()
When the functions are called they all print 4
. I would like them to print the actual value of i
from when they were created, so 0
, 1
, 2
, 3
, and 4
. This is all part of a large multithreaded project, which I need to use this blueprint.
You need to pass i as an argument in lambda funcion
fun_list = [lambda x=i: foo(x) for i in range(5)]