[Python-ideas] Changing semantics of for-loop variable

Greg Ewing greg.ewing at canterbury.ac.nz
Fri Sep 30 12:03:55 CEST 2011

Nick Coghlan wrote:
> I'm not sure how we could handle the following pathological case:
> def outer():
>     i = 0
>     def loop():
>         nonlocal i
>         for i in range(10):
>             def inner():
>                 return i
>             yield inner
>     def shared():
>         return i
>     return loop, shared

Yeow. That's nasty indeed.

Really handling it properly would require cells containing cells,
which could get quite tricky.

I'm inclined to punt and say that you deserve whatever you get if
you do that. In any of the intended use cases, the loop variable
will be local.

> If we did this, I think we'd have to make reusing a nonlocal reference
> as a loop variable a SyntaxError

That might be a bit harsh, since it would make currently valid
code illegal.

Another possibility would be to say that the new semantics only
apply when the loop variable is local; if it's declared nonlocal
or global, the old semantics apply.


More information about the Python-ideas mailing list