0

Can someone explain why in the following example all functions are the same after running? Is there a way to avoid this and get the distinct function I want (please don't suggest using partial).

def lin_fun(x, a, b):
    return a*x + b

funs = {}
params = [(1,2), (3,4)]

for param in params:
    funs[param] = lambda x: lin_fun(x, *param)
    
print(funs[params[0]](100))
# prints 304
print(funs[params[1]](100))
# prints 304
AMC
  • 2,642
  • 7
  • 13
  • 35
lbf_1994
  • 239
  • 2
  • 9

1 Answers1

1

Because of how name binding in loops works.

You'll need one more stack frame to properly capture values:


def bind(f, *params):
    return lambda x: f(x, *params)

for param in params:
    funs[param] = bind(lin_fun, *param) 
AKX
  • 152,115
  • 15
  • 115
  • 172