Question 4
Back to Exercise
Each handler should print its own label. Which statement correctly identifies the bug?
handlers = []
for label in ["Save", "Open", "Exit"]:
handlers.append(lambda: "clicked " + label)
print([h() for h in handlers])
- A append() copies the last lambda three times
- B Strings cannot be used in lambdas
- C The list comprehension calls the wrong handler
- D The lambdas look up label when called, after the loop ended on "Exit"; capture it with lambda label=label: … Correct
Correct Answer: Option D
Late binding: free variables are resolved at call time. functools.partial also captures the current value.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!