[Python-ideas] For-loop variable scope: simultaneous possession and ingestion of cake
Bruce Leban
bruce at leapyear.org
Mon Oct 6 09:08:46 CEST 2008
On Sun, Oct 5, 2008 at 10:16 PM, Carl Johnson <carl at carlsensei.com> wrote:
> On 2008/10/05, at 6:47 pm, Bruce Leban wrote:
>
> 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".
>
Yup. I wrote that a bit too quickly.
>
>
>> 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".
>
>
Consider this:
i = 0
def f():
global i
i += 1
return lambda: immanentize 1
when does immanentize get evaluated? when f is defined or when the lambda is
evaluated? From what you wrote, it sounds like you think it's evaluated when
f is defined. OK, so how do I get the equivalent of:
def f():
global i
i += 1
lambda i=i: i
using immanentize?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20081006/4ad6c1af/attachment.html>
More information about the Python-ideas
mailing list