[Python-ideas] For-loop variable scope: simultaneous possession and ingestion of cake
arnodel at googlemail.com
Sat Oct 4 09:25:54 CEST 2008
On 4 Oct 2008, at 05:12, Greg Ewing wrote:
> Terry Reedy wrote:
>> Your intended-to-be-motivating example ... is a toy snippet that
>> illustrates some points of Python behavior, but which I see no use
>> for in real application code.
> My example wasn't intended to prove the existence of the
> problem, only refer to an already-acknowledged one. Its
> existence is attested by the fact that people regularly
> get tripped up by it.
> Here's a more realistic example:
> menu_items = [
> ("New Game", 'new'),
> ("Resume", 'resume'),
> ("Quit", 'quit')
> buttons = 
> for title, action in menu_items:
> buttons.append(Button(title, lambda: getattr(game, action)()))
Isn't this better as:
buttons.append(Button(title, getattr(game, action)))
Unless you want late binding of 'game', but that would be confusing.
> which gives you three buttons that all execute the
> 'quit' action.
More information about the Python-ideas