0

I need to generate a list of slightly different functions to be dynamically constructed:

def f(p,x):
    print("f", p, x)

a=[]
for param in ('param_A', 'param_B'):
    a.append( lambda x: f(param, x) )

Result:

IN:    a[0](0)
OUT:   f param_B 0
IN:    a[1](1)
OUT:   f param_B 1

While I will probably solve the problem by using functors instead, would be interesting to know the mechanics of variable binding and what is the simple fix for the above example

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
Muposat
  • 1,476
  • 1
  • 11
  • 24
  • 1
    *"what is the simple fix?"*: `lambda x, param=param: ...`. See http://stackoverflow.com/q/12423614/3001761 – jonrsharpe Jul 20 '15 at 19:34
  • @NightShadeQueen that's *inside* the lambda, so won't work, and puts a positional argument after a keyword one. – jonrsharpe Jul 20 '15 at 19:35

0 Answers0