Search code examples
pythonlambdaclosureslazy-evaluation

Define a list of lambdas in Python that is eagerly evaluated


I'd like to programmatically create a list of functions, each of which returns a dictionary with a specific key, and always the same value. That is:

l1 = [lambda _: {0: 42}, lambda _: {2: 42}, lambda _: {3: 42}]

I'm trying to achieve the same result programmatically. To try and avoid the usual problem with lazy evaluation, I thought I'd only need to create a generator for generating the functions on the fly:

gen = (lambda _: {f: 42} for f in range(3))

And then use a simple list comprehension to get the list:

l2 = [f for f in gen]

That's not sufficient. In fact, if you compare func_clousures with one another, they're all the same:

x[0].func_closure == x[1].func_closure == x[2].func_closure  # this is True

What's the best way to get the result I'm looking for?


Solution

  • You are assigning the last value of f to all the lambdas:

    gen = (lambda _,f=f: {f: 42} for f in range(3))
    

    As @Jon Clements so kindly pointed out the term is lazy binding, which is described in Common_Gotchas_In_Python