Question
In the code below I have defined a function func
which takes in one input and simply prints it. Then I create a list, data
, containing two empty dict
objects, before populating them with a random number and a lambda pointing to func
with the random number as input. Next, I print the list using json.dumps
to show the content. Then I iterate over the list and call the lambda function contained in each dict - The output shows that func
is called with the correct inputs. Lastly, I get the dicts in the list by indexing it, and then calling the lambda function as before - Now we see that func
is no longer called with the correct inputs.
I'm wondering what is happening here?
>>> from random import random
>>> import json
>>> def func(x):
... print('x:', x)
>>> data = [dict(), dict()]
>>> for d in data:
... d['x'] = random()
... d['f'] = lambda: func(d['x'])
>>> print(json.dumps(data, indent=4, default=str))
[
{
"x": 0.6519067978068578,
"f": "<function <lambda> at 0x00000238E2672F78>"
},
{
"x": 0.48881125686952465,
"f": "<function <lambda> at 0x00000238E2678048>"
}
]
>>> for d in data:
... d['f']()
x: 0.6519067978068578
x: 0.48881125686952465
>>> data[0]['f']()
x: 0.48881125686952465
>>> data[1]['f']()
x: 0.48881125686952465
Solution 1
from random import random
def func(x):
print('x:', x)
def make_lambda(x):
return lambda: func(x)
data = [dict(), dict()]
for d in data:
d['x'] = random()
d['f'] = make_lambda(d['x'])
Solution 2
from random import random
def func(x):
print('x:', x)
data = [dict(), dict()]
for d in data:
d['x'] = random()
d['f'] = lambda x=d['x']: func(x)