Python: lambdas in a for loop

Question:

I’m unsure where I’m going wrong with the below – I’m sure it’s something basic but I’m still a bit unsure what the issue is. I’m trying to have a button change the range of the car when clicked, but it will only set the last one.

    def draw:
        car_column = 0
        for car in boarding_cars:
            tk.Label(transport_frame, text="{}".format(car.name)).grid(row=0, column=car_column)
            tk.Button(transport_frame, text=car.range, command= lambda: change_range(car)).grid(row=1, column=car_column)
            car_column += 1

    def change_range(car):
        print car.name
        if car.range == "mid":
           car.range = "close"
        elif car.range == "close:
           car.range = "mid"

I understand it’s just setting everything as the last one in the list, but I’m unsure how to stop it doing that. Any help would be appreciated.

Asked By: Retro

||

Answers:

This is a common problem when people don’t understand that lambda is late-binding. You need to use partial instead for this.

from functools import partial

tk.Button(transport_frame, text=car.range, command= partial(change_range, car)).grid(row=1, column=car_column)
Answered By: Novel
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.