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

Carl Johnson carl at carlsensei.com
Mon Oct 6 07:16:46 CEST 2008


On 2008/10/05, at 6:47 pm, Bruce Leban wrote:

> Um, I think this is more complicated. Consider:
>
>    i = 0
>    def f():
>         i += 1
>         return lambda: i
>

I'm not sure I see what you're getting at. In Python 2.6 and 3.0rc1  
this raises "UnboundLocalError: local variable 'i' referenced before  
assignment." If you want to do what it looks like you want to do, you  
have to use "nonlocal i" or "global i".


> Now lambda: i is bound to i so every time I call f it will return a  
> function that returns the current value of i not the one at the time  
> f was called. So I can fix this by immanetization:
>
>    i = 0
>    def f():
>         i += 1
>         return lambda: immanentize i
>
> This will return lambda: 1, then lambda: 2, etc. right? No. It  
> returns lambda: 0, lambda: 0, etc.

To me, it is transparently clear that this will return lambda: 0 every  
time. That's what immanentization does. If you want lambda: 1, etc.,  
use "nonlocal i".

-- Carl



More information about the Python-ideas mailing list