[Python-ideas] For-loop variable scope: simultaneous possession and ingestion of cake

Greg Ewing greg.ewing at canterbury.ac.nz
Sat Oct 4 06:12:15 CEST 2008


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)()))

which gives you three buttons that all execute the
'quit' action.

-- 
Greg





   Given def f(i): return i; your lst[i]() is
> equivalent to f(i).  So just write and use the function.
> 
> OK, to be persnickety, we need more code, of about the same length as 
> needed to generate lst:
> 
> def f(i):
>   if not isinstance(i,int): raise TypeError("requires int i")
>   if not -10 <=i <10: raise ValueError("requires -10 <= i < 10")
>   return i
> 
> So, as near as I can see, your list of identical functions with variant 
> closure cells simulates type and range checking.  What is the point of 
> that?
> 
> Perhaps you have an undisclosed real use case with much more complicated 
> closures.  It would still be true that the array index could instead to 
> fed to the function as an arg.  If there were really a reason not to do 
> that, the 15 keystroke overhead would be relatively much smaller for 
> more complicated (and realistic) closures.
> 
> Terry Jan Reedy
> 
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas




More information about the Python-ideas mailing list