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

Neil Toronto ntoronto at cs.byu.edu
Sat Oct 4 01:48:12 CEST 2008


Andrew Clover wrote:
> Greg Ewing wrote:
> 
>  > 1. If the loop variable is referenced by such a nested
>  >    function, a new local scope is effectively created
>  >    to hold each successive value of the loop variable.
> 
> Why only the loop variable? What about:
> 
>     >>> for i in range(3):
>     ...     j= str(i)
>     ...     funs.append(lambda: j)
>     >>> funs[0]()
>     '2'

Spanking good point. To hack this "properly" all cell variables closed 
over within the loop would have to go into the per-iteration scope.

> It seems an odd sort of scope that lets rebindings inside it fall 
> through outwards.

True, but a lot of Python programs would depend on this - even new ones 
because of social inertia.

>> Also, most other languages which have lexical scoping
>> and first-class functions don't seem to suffer from
>> problems like this.
> 
> That's not always because of anything to do with introducing scopes 
> though. Some of those languages can bind the variable value early, so if 
> you were to write the equivalent of:
> 
>     >>> i= 3
>     >>> f= lambda: i
>     >>> i= 4
> 
> f() would give you 3. I would love to see an early-value-binding 
> language with similar syntax to Python, but I can't see how to get there 
> from here.

Python could close over the values rather than a cell. That's *almost 
always* what people really care about anyway! It'd break almost no code.

Of course, to satisfy Paul Graham, there'd have to be a way to go back 
to cells. A "cell" keyword? Other languages make this explicit - they're 
often called "boxes". I wonder if "nonlocal" could go if there were a 
"cell" keyword...

It wouldn't mean the variable carries pass-by-reference semantics, 
though. That would be bad.

Neil



More information about the Python-ideas mailing list