Lambda inside FORs: Delay execution correctly?

mail@pastecode.io avatar
unknown
python
2 years ago
1.3 kB
3
Indexable
Never
def process_and_save_data(mydata):
    print(f"Data {mydata}")
    return f"processed {mydata}"
data_list = ["data1", "data2", "data3"]


## (1) Wrong way
# In this case the execution is delayed, but the result will all use the data 3
result_builder = []
for data in data_list:
    result_builder.append(lambda: process_and_save_data(data))

for result in result_builder: print(result())
""">>
Data data3
processed data3
Data data3
processed data3
Data data3
processed data3
"""

## (2) Almost right way
# In this case the result is correct, but the function runs during the for
result_builder = []
for data in data_list:
    result_builder.append((lambda f: (lambda: f))(process_and_save_data(data)))

for result in result_builder: print(result())

""">>
Data data1
Data data2
Data data3
processed data1
processed data2
processed data3
"""

## (3) Result I want, but no for
# In this case the function is delayed and called with the right values, but obviously not scalable
result_builder = [
    lambda: process_and_save_data(data_list[0]),
    lambda: process_and_save_data(data_list[1]),
    lambda: process_and_save_data(data_list[2]),
]

for result in result_builder: print(result())

""">>
Data data1
processed data1
Data data2
processed data2
Data data3
processed data3
"""