electricman electricman - 2 months ago 7
Python Question

Python generating a lookup table of lambda expressions

I'm building a game and in order to make it work, I need to generate a list of "pre-built" or "ready to call" expressions. I'm trying to do this with lambda expressions, but am running into an issue generating the lookup table. The code I have is similar to the following:

import inspect

def test(*args):
string = "Test Function: "
for i in args:
string += str(i) + " "
print(string)

funct_list = []

# The problem is in this for loop
for i in range(20):
funct_list.append(lambda: test(i, "Hello World"))

for i in funct_list:
print(inspect.getsource(i))


The output I get is:

funct_list.append(lambda: test(i, "Hello World"))
funct_list.append(lambda: test(i, "Hello World"))
funct_list.append(lambda: test(i, "Hello World"))
funct_list.append(lambda: test(i, "Hello World"))
...


and I need it to go:

funct_list.append(lambda: test(1, "Hello World"))
funct_list.append(lambda: test(2, "Hello World"))
funct_list.append(lambda: test(3, "Hello World"))
funct_list.append(lambda: test(4, "Hello World"))
...


I tried both of the following and neither work

for i in range(20):
funct_list.append(lambda: test(i, "Hello World"))

for i in range(20):
x = (i, "Hello World")
funct_list.append(lambda: test(*x))


My question is how do you generate lists of lambda expressions with some of the variables inside the lambda expression already set.

Answer

Use default arguments for the lambda:

for i in range(20):
    funct_list.append(lambda i=i: test(i, "Hello World"))